Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  88] [ 3]  / answers: 1 / hits: 72096  / 10 Years ago, sun, march 9, 2014, 12:00:00

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!


More From » node.js

 Answers
11

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.


[#72087] Thursday, March 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denis

Total Points: 260
Total Questions: 87
Total Answers: 87

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;