foobar
foobar

Reputation: 11374

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

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, if 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?

Upvotes: 4

Views: 407

Answers (2)

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

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);
      });

Upvotes: 0

generalhenry
generalhenry

Reputation: 17319

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

Upvotes: 3

Related Questions