Search⌘ K
AI Features

Updating Documents: findOneAndUpdate() and updateMany()

Explore how to update documents in MongoDB with Mongoose using findOneAndUpdate and updateMany. Understand the importance of returning updated documents with the new option, using $set to avoid data loss, and how to handle single and bulk updates effectively.

Update operations are where small mistakes often create confusing bugs. A handler updates a document and returns the result, but the client still sees the old values because the method returned the pre-update document. That behavior is controlled by the { new: true } option and often surprises developers who are new to Mongoose. This lesson explains Mongoose update methods and two rules that prevent common update errors: return the updated document and use partial updates instead of replacing the whole document.

As with reads, single-document updates target the business identifier id, so the method is findOneAndUpdate({ id }, ...), not findByIdAndUpdate().

Note: The examples are runnable against the seeded ecommerce database. Each opens a local connection, runs one update, and prints the result.

To make the path concrete, the next visual should show an update request returning the modified document:

Update request flow returning the modified document
Update request flow returning the modified document
...