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, 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);
});
精彩评论