mongoose difference of findOneAndUpdate and update

DatabaseMongodbMongooseSql Update

Database Problem Overview


What is the difference between findOneAndUpdate and update?

Both accept criteria to query and doc to update.

Database Solutions


Solution 1 - Database

Well there is the respective documentation to view for both .update() and .findAndModify() which is the root method of .findOneAndUpdate() here.

But in the main differences there are:

  • update(): Is meant to perform an atomic update operation against "one or more" documents matched by it's query condition in a collection. It returns the number of modified documents in it's response.

  • findOneAndUpdate(): Has the purpose of both processing an update statment on a "singular" document, as well as retrieving the content of that "singular" document. The state returned depends on the value of the "new" option as passed to the operation. Where true the "modified" document is returned. Where false the "original" document is returned before any modification. The latter form is the default option.

In short. One is meant to modify in "bulk" and not worry with the document content in result. And the other is meant to modify a singular document and return the document content in result.

That's the difference.

Solution 2 - Database

The .findOneAndUpdate method issues a mongodb .findAndModify update command and returns the found document (if any) to the callback or return the modified document rather than the original if the new option is true and the .update execute the query as an update() operation.

Solution 3 - Database

Note there is an option returnNewDocument in the findOneAndXXX methods and it's default value is true. If you are using the node.js driver, the options is called returnOriginal.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSooCheng KohView Question on Stackoverflow
Solution 1 - DatabaseBlakes SevenView Answer on Stackoverflow
Solution 2 - DatabasestyvaneView Answer on Stackoverflow
Solution 3 - DatabaseclarkttfuView Answer on Stackoverflow