skip to Main Content

I have the below code

Product.findOneAndUpdate({ name: 'Cycling Jersey' }, { onSale: true }, { new: true })
    .then(data => {
        console.log("IT WORKED!")
        console.log(data);
    })
    .catch(err => {
        console.log("OH NO ERROR!")
        console.log(err)
    })

It updates the databse, and prints the updated document to the terminal, however, when I have only the below line

Product.findOneAndUpdate({ name: 'Cycling Jersey' }, { onSale: true }, { new: true })

The update doesn’t happens. It should happen right? The .then is just to notify me when the update has completed, but if I don’t use .then it should update the database in background atleast. If I open Mongo Shell after 5 mins or more, nothing has changed in Database, why is that so?

2

Answers


  1. This was surprisingly difficult to answer. However both the documentation and the source code show that this method doesn’t really start the operation and return a promise. Instead it configures the query object to carry out the operation, and returns the query object. However the query object itself has a “then” method, which does start the real action and return a promise.

    So you are right: nothing really happens until you call then().

    This may have been done to allow additional chained calls to override or adjust the query before then() is called.

    Although you chose to write your then() calls by hand, is worth noting that this method is also compatible with the “await” keyword because that keyword actually works with any “thenable” (any object with a “then” method attached that behaves like it would on a promise), it doesn’t strictly require a promise.

    Login or Signup to reply.
  2. Mongo queries are not promises. They are thenables, there is a difference. They are thenables to give the convenience of using the results after the completion of the command.

    But that does not mean that the commands run as soon as you call the function.

    This is from the docs:

    Mongoose queries are not promises. Queries are thenables, meaning they have a .then() method for async/await as a convenience. However, unlike promises, calling a query’s .then() executes the query, so calling then() multiple times will throw an error.

    There are two ways to execute the query. By using the then()/await() or by using the callback function as second parameter.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search