To modify a field in an existing entry in mongoose, what is the difference between using
model = new Model([...]) model.field = 'new value'; model.save();
and this
Model.update({[...]}, {$set: {field: 'new value'});
The reason I'm asking this question is because of someone's suggestion to an issue I posted yesterday: NodeJS and Mongo - Unexpected behaviors when multiple users send requests simultaneously. The person suggested to use update instead of save, and I'm not yet completely sure why it would make a difference.
Thanks!
MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
Working with save() When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.
1 Answer. The . save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.
Two concepts first. Your application is the Client, Mongodb is the Server.
The main difference is that with .save()
you already have an object in your client side code or had to retrieve the data from the server before you are writing it back, and you are writing back the whole thing.
On the other hand .update()
does not require the data to be loaded to the client from the server. All of the interaction happens server side without retrieving to the client.So .update()
can be very efficient in this way when you are adding content to existing documents.
In addition, there is the multi
parameter to .update()
that allows the actions to be performed on more than one document that matches the query condition.
There are some things in convenience methods that you lose when using .update()
as a call, but the benefits for certain operations is the "trade-off" you have to bear. For more information on this, and the options available, see the documentation.
In short .save()
is a client side interface, .update()
is server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With