Reputation: 20591
Please take a look at following example:
const myDoc = await model.findById(id).exec();
// here runs long running operation which can take about 2-3 secs
myDoc.name = "Updated Name";
myDoc.save()
Is it OK to update document using this pattern? What if between checking out document and saving it (it takes 2-3 secs) some another piece of code will try to update this document? It means changes from another code will not be saved?
If yes, does it mean it's better to do updates on MongoDB side using findOneAndUpdate
and similar methods?
Upvotes: 2
Views: 240
Reputation: 4619
find
followed by save
is nothing more than updating a document with all fields. You might as well don't find
and just update
the document with all fields filled anew.
The time lapse between finding and saving could be anywhere from few seconds to many minutes. For instance, an edit form being shown to user (find
) who modifies some fields and clicks update button (save
) after 15 minutes; any changes made in between by some other clients will be overridden.
findOneAndUpdate
and similar methods are atomic and server-side(mongo), which handles concurrency with locking. Unless you need to process a document then save, I think update
methods are generally better suited. This and this SO replies do a good job in answering similar questions.
Upvotes: 0
Reputation: 1008
Remember that eventual consistency is the model. Mongo will be eventually consistent so its only somewhat true that changes will affect other changes; but its important to note that most of the time this is non blocking on the mongo side.
So the real answer is no... but the kinda answer is yes but it will eventually correct itself.
save() being an antipattern? Thats really up to you.. if you are taking more OO rather than functional I think its okay to use
Upvotes: 1