node

Mongoose UpdateOne() example


There are various methods available in mongoose to update the document like .save(), findOneAndUpdate(), updateOne(). Each method has it’s own benefits. In today’s post, we are going to use updateOne() & see what is the main difference between update & update one method.

updateOne():

There are multiple documents saved inside MongoDB which match the criteria of update condition. updateOne method matches the first document that satisfies the condition & updates it. By default, updateOne() returns the number of documents matched & a number of documents modified.

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

const oldDocument = await User.updateOne(filter, update);
oldDocument.n; // Number of documents matched
oldDocument.nModified; // Number of documents modified

There are various options available that you can pass along with filter & update. 

  • timestamps: boolean value that allows you to overwrite timestamps.
  • upsert: boolean value that allows you to create a new document if no matching document is found.
  • strict: boolean value that overwrites the schema’s strict mode option.

Difference between .update() & updateOne():

The main difference between these two methods is updateOne only updated the first matching documents unlike the update(), which supports the multi or overwrite options.


Share on social media

//