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
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.
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:
There are two ways to execute the query. By using the
then()/await()
or by using the callback function as second parameter.