Is it possible to use multi.incr(value)
with multi.hmset
?
I mean:
var name = \'Josh\';
var multi = client.multi();
multi.incr(\
The accepted answer above is unnecessarily complicated. You do not need to use a multi or watch in this circumstance. INCR is already atomic, and is designed for this exact scenario. Edit: Thanks to Itamar Haber & robe007 for getting the accepted answer changed. :)
You can simply do this:
var name = 'Josh';
client.incr('id', function(err, id) {
client.hmset('user:' + id, 'username', name);
});
By doing the above, INCR automatically locks the "id" key, increments it for you, unlocks it, and returns it to you. Thus, there is no way for anyone to get a duplicate user id using the code above. It also has the benefit of never really being able to fail, unlike WATCH/GET, where you'd have to check for failures and run your queries again if they failed.