Locks in Mongo and Nodejs
<p>I'm trying to build a really simple shopping app, where users can buy items with virtual currency.</p>

<p>I'm using multiple NodeJS processes for this, so I'm scared about the async part of things.</p>

<p>This is what I do:</p>

<pre><code>app.post('/buy', function(req, res){

    User.findOne({_id: req.userId}, function(err, user){

        if(user.balance &gt;= ITEM_PRICE){

            User.decrementBalance({_id: req.userId}, function(err){

                //Do transaction, give item to user, etc

            });

        } else {
            //Not enough money
        }
    });
});
</code></pre>

<p>The problem with this approach is that users can submit multiple /buy requests in a very short time frame. This might lead to a race condition where the second request checked the user's balance before the first one can decrement it. This results in the user having a negative value and taking out much more items than what his balance allowed him to.</p>

<p>Is there a way to solve this? I'm thinking of doing an User.update() and verifying if the user was modified or not. Could that work?</p>