marcello3d / node-mongolian

[project inactive] Mongolian DeadBeef is an awesome Mongo DB driver for node.js
https://groups.google.com/group/node-mongolian
zlib License
350 stars 50 forks source link

collection.update just work the first time and is ignored after that #109

Closed BeMoreDifferent closed 11 years ago

BeMoreDifferent commented 11 years ago

Hi. I have a strange problem. I try to update some collection really often. It`s mostly the same system like a usercounter- script: if key is give update key +1 else creat key. This script looks like this:

    for(var i = 99; i >= 0; i--) {
        collection.findOne({ n : name }, function(err, p) {
        if(!err && typeof(p) == 'object'){
            p.t = p.t++;
            collection.update({ _id : p._id }, p );
        }else{
            collection.insert(z);
        }           
        });
    };

If I submit this script the collection get updated ones while there are 100 loops wich should update the collection. How can i solve this problem? Did I miss anything?

Hope anybody can help me Daniel

marcello3d commented 11 years ago

You've create a race condition. Basically you have 100 findOne's happening simultaneously. They're most likely all going to return values before any of the updates happen. Look into using an atomic increment in the update call.

BeMoreDifferent commented 11 years ago

Nice. It works and is amazing fast. By the way: you did a great job with creating this module :) Thank you for building it