I am using MongoDB with NodeJS. Therefore, I use mongoose.
I am developing a real-time multiplayer game. Therefore, I receive many requests from many players, sometimes at the same time.
I can simplify this by saying that I have a home collection that looks like this:
{
"_id" : 1,
"items": [item1, item2, item3]
}
I have a static function called after each request:
house.statics.addItem = function(id, item, callback){
var HouseModel = this;
HouseModel.findById(id, function(err, house){
if (err) throw err;
if (house.items.length < 4){
HouseModel.findByIdAndUpdate(id, {$push: {items: item}}, cb);
}
});
}
In this example, I have encoded so that there are housenever more than 4 elements in a document . But it happens that when I receive several requests at the same time, this function is executed twice on both requests, and since it is asynchronous, they both click on a new element in the element field, and then my house has 5 elements.
- ? ?