开发者

I think this code involving NodeJs and MongoDb might fail, how to fix it?

开发者 https://www.devze.com 2023-02-17 21:06 出处:网络
This seems like a general database question, but I\'ll ask it in my current context of NodeJs + MongoDb.

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

Say we have some universal counter with id "xyz". Here's the piece of code to fetch the latest count 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, i开发者_C百科f two clients are trying to call this code at the same time, then both clients may get the same count, then the collection updates the count twice - not desirable! How to fix this?


$inc is atomic, no risk there. It's keeping from the outer find that doesn't work.

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

is likely what you want.


You can use findAndModify, it modifies the object and returns the updated version. This guarantees that each caller will get incremented value.

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

精彩评论

暂无评论...
验证码 换一张
取 消