Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 behaviours when multiple users send requests simultaneously. The person suggested to use update instead of saving, and I'm not yet completely sure why it would make a difference.

Thanks!

2 Answers

0 votes
by (106k points)

You can understand the difference between these two concepts by reading below answer:-

The .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.

0 votes
by (107k points)

There are some things that are in conventional methods that you may lose when using .update() as a call, but the profits for certain operations are the "trade-off" you have to bear. In short .save() is a client-side interface, .update() is server-side. The update is more structured than find followed by save because it avoids loading the whole document. It's important to note that on save, Mongoose internally differentiates the document and only sends the fields that have actually changed. This is good for atomicity. Another point is that by default validation is not run on update but it can be enabled.

Related questions

0 votes
2 answers
0 votes
2 answers
0 votes
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...