return modified object after update in Mongoose

Return Modified Object after Update in Mongoose

When working with MongoDB and Mongoose, updating documents is a common operation. After updating a document, we might want to return the updated object for further processing. In this post, we will explore how to return the modified object after update in Mongoose.

Using findByIdAndUpdate()

The simplest way to update a document and return the modified object in Mongoose is by using the findByIdAndUpdate() method. This method takes in the ID of the document to be updated, the update object, and an options object. By default, findByIdAndUpdate() returns the original document before it was updated. To return the modified document instead, we need to set the new option to true.

const updatedDocument = await Model.findByIdAndUpdate(id, updateObject, { new: true });

In the code above, Model is the name of our Mongoose model, id is the ID of the document to be updated, and updateObject is an object containing the fields to be updated. The await keyword indicates that we are using an asynchronous function and we are waiting for the result of the update operation before continuing.

Using findOneAndUpdate()

The findOneAndUpdate() method works similarly to findByIdAndUpdate(), but instead of taking an ID, it takes a query object as the first argument. This allows us to update a document based on any field instead of just the ID.

const updatedDocument = await Model.findOneAndUpdate(queryObject, updateObject, { new: true });

In the code above, queryObject is an object containing the fields to search for and updateObject is an object containing the fields to be updated.

Other Options

There are other options we can pass to findByIdAndUpdate() and findOneAndUpdate() to customize their behavior. For example, we can set the runValidators option to true to run validators on the updated fields. We can also set the upsert option to true to create a new document if the query does not match any documents.

// Run validators on updated fields
const updatedDocument = await Model.findByIdAndUpdate(id, updateObject, { new: true, runValidators: true });

// Create a new document if query does not match any documents
const updatedDocument = await Model.findOneAndUpdate(queryObject, updateObject, { new: true, upsert: true });

In summary, we can use the findByIdAndUpdate() and findOneAndUpdate() methods in Mongoose to update documents and return the modified object. By setting the new option to true, we can ensure that the modified object is returned instead of the original document. We can also pass other options to customize the behavior of these methods.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe