node

How to use Mongoose findOneAndUpdate


Mongoose provides various methods to update the document like .save(), findOneAndUpdate(), updateOne(). In today’s post we are going to use findOneAndUpdate().

findOneAndUpdate():

There are multiple documents saved inside mongoDB which match the criteria of update condition. findOneAndUpdate method matches the first document that satisfies the condition & updates it. By default, findOneAndUpdate() returns the original document as it was before update method was applied.


const filter = { name: 'John Doe' };
const update = { age: 30 };

const oldDocument = await User.findOneAndUpdate(filter, update);
oldDocument.name; // 'John Doe'
oldDocument.age; // 29

const updatedDocument = await User.findOneAndUpdate(filter, update, {
  new: true
});

updatedDocument.name; // 'John Doe'
updatedDocument.age; // 30

If you want the updated document to be written just pass  new options set to true. returnOriginal is another parameter that identifies whether an updated document will be written or not. If you set returnOriginal: false it will return the updated document.

Difference between .save() & findOneAndUpdate():

The main difference between these two method is findOneAndUpdate is atomic in nature which means the document does not change between MongoDB finding & updating the document. On the flip side .save() does not guarantee atomic update.


Share on social media

//