I searched a lot but could not find a clear solution, although my scenario is super standard. In the code below I'm checking if ID exists. Then:
If ID doesn't exist, a record is inserted with count=1.
Otherwise, count is increased by 1
req.db.collection('names_table').count({_id: name}, function (e, result) {
if (e) { return next(e); }
if (result === 0) { //name not yet exists
var new_name = { "_id": name, count:1; };
db.collection('names_table').insert(new_name, function (e) {
if (e) { return next(e); }
debug('name ' + name + ' created successfully');
res.redirect('back');
});
} else {
debug('increasing name ' + name + ' to ' + result);
var update_name = { '$inc': { "count": 1 } };
db.collection('names_table').update({_id: player_id}, update_name, function (e) {
if (e) { return next(e); }
debug('Updated!');
res.redirect('back');
});
}
});
How can I make sure that between {decision that the ID doesn't exist} and {new id is inserted}, no other thread will come and repeat the same logic and also try to insert after testing if exist?
upsert
you can create or update atomically. But in case of multiple simultaneous requests, the last write wins.