Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose difference between .save() and using update()

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!

like image 982
Edward Sun Avatar asked Mar 09 '14 05:03

Edward Sun


People also ask

What is difference between save and update method in MongoDB?

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.

What does save () do in Mongoose?

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.

Does update call save in Mongoose?

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.

What is difference between create and save in Mongoose?

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.


1 Answers

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.

like image 87
Neil Lunn Avatar answered Sep 19 '22 11:09

Neil Lunn