This content originally appeared on CodeSource.io and was authored by Deven
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.
The post Mongoose UpdateOne() example appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-10-19T05:26:21+00:00) Mongoose UpdateOne() example. Retrieved from https://www.scien.cx/2021/10/19/mongoose-updateone-example/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.