简体   繁体   English

使用mongodb操作运行for-in循环

[英]Running for-in loop with mongodb operations

I have some function like this... 我有这样的功能......

for(key in object){
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.update(...);
    })
};

However, the value of key changes before the mongodb calls are complete, ie the loop goes into next iteration. 但是,在mongodb调用之前键的值发生变化,即循环进入下一次迭代。 Is there a way to do it in sequential manner. 有没有办法按顺序进行。 Or is there something for objects like async.map() for arrays? 或者是否有像async.map()这样的对象用于数组?

All the calls to your callback will happen after all the iterations of the loop have taken place, so when they get executed the value of key will be whatever is its last value. 在回调的所有迭代发生之后,所有对回调的调用都会发生,所以当它们被执行时, key的值将是它的最后一个值。

One common solution is to wrap all your calls in a closure: 一个常见的解决方案是将所有调用包装在一个闭包中:

for(key in object){
    (function(key, value) {
        db.collection.findOne(criteria, function(err, doc){
            // ...
            db.collection.insert(...);
        })
    })(key, object[key]);
};

Another way you could achieve the same thing is to use the Object.keys() method (which creates an array out of the keys in your object) and call Array#forEach on the array. 另一种可以实现相同目的的方法是使用Object.keys()方法(从对象中的键创建一个数组)并在数组上调用Array#forEach That way you can skip the extra closure because forEach already has a function callback: 这样你就可以跳过额外的闭包,因为forEach已经有一个函数回调:

Object.keys(object).forEach(function(key) {
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.update(...);
    })
});

Which is arguably a bit more elegant 这可以说有点优雅

You could build up a closure to save the value of key 您可以构建一个闭包来保存key的值

for(key in object){
  (function(ky) { 
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.insert(...);
    })
  })(key)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM