I think this code involving NodeJs and MongoDb may fail, how can I fix it?

This seems like a general database question, but I will ask it in my current context of NodeJs + MongoDb.

Say we have a universal counter with id "xyz". Here is a code snippet to get the last score and increase it by 1:

collection.find({id: "xyz"}, function(err, currentCount) { collection.update({id: "xyz"}, {$inc: {count: 1}}, function(err, data) { cb(currentCount); } } } 

The problem is that if two clients try to call this code at the same time, then both clients can get the same account, then the collection updates the account twice - it is undesirable! How to fix it?

+4
source share
2 answers

$ inc is atomic, no risk. He keeps from an external find that does not work.

 collection.update({id: "xyz"}, {$inc: {count: 1}}, function(err, data) { cb(data); } } 

most likely what you want.

+3
source

You can use findAndModify, it modifies the object and returns an updated version. This ensures that each caller receives an increased value.

 collection.findAndModify( {id: 'xyz' }, ['_id'], {$inc: {count: 1}}, function (err, data) { cb(data); }); 
0
source

Source: https://habr.com/ru/post/1344050/


All Articles