Mongoose updateOne vs save methods

Viewed 785

There are few ways to update the document record in MongoDB database. With the User model defined I can find the user first, then modify its attribute and save it with the save() method:

let user = await User.findOne({"email": "user@email.com"});
user["email"] = "another@email.com";
await user.save();

Another option would be to use updateOne method instead of save:

await user.updateOne({"email": "another@email.com"});

Why would I choose to use the updateOne method over the save? What are the pros and cons?

1 Answers

I believe in your first example it requires 2 separate queries to your database, so less performant. One to find the document, and then another to save (update it). Though the benefit of doing it this way is if you have validation setup in your schema, then it would check the validation before updating.

The second one you only do one query and it's done. This however won't check your validations. Though you can opt-in by passing runValidators:true:

await user.updateOne({"email": "another@email.com"}, {"email": "another@email.com"}, { runValidators: true });
Related