Manuel Di Iorio Manuel Di Iorio - 2 months ago 18
Node.js Question

In mongoose, is model.save atomic for increment or should I always use $inc?

I need to increment the likes field of a record in MongoDB and mongoose, but I'm little 'worried' about atomicity of these operations, as this should be concurrently-safe:

Post.findById(id, function(err, post) {
post.update({$inc: {
likes: 1
}});
});


vs

Post.findById(id, function(err, post) {
post.likes++;
post.save()
});


Do they provide the same secure result? Think about the fact that I have even to decrement the likes of the record (e.g. if the user clicks again on the like button)

Post.findById(id, function(err, post) {
post.update({$inc: {
likes: -1
}});
});

Answer

MongoDB $inc is an atomic operation within a single document (see mongoDB documentation).

In the second case, the operation is not atomic, because when the model is saving, another request could be sent, and the loaded likes will have the previous value.