连续迭代mongodb游标(在移动到下一个文档之前等待回调)

时间:2013-08-08 06:36:14

标签: node.js mongodb mongoskin async.js

使用mongoskin,我可以执行这样的查询,它将返回一个游标:

myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

      }
}

但是,我想为每个文档调用一些异步函数,并且只有在调用它之后才转移到游标上的下一个项目(类似于async.js模块中的eachSeries结构)。 E.g:

myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {

            externalAsyncFunction(result, function(err) {
               //externalAsyncFunction completed - now want to move to next doc
            });

      }
}  

我怎么能这样做?

由于

更新

我不想使用toArray(),因为这是一个大批量操作,结果可能不会一次性适合内存。

9 个答案:

答案 0 :(得分:49)

如果您不想使用toArray将所有结果加载到内存中,则可以使用如下所示的光标进行迭代。

myCollection.find({}, function(err, resultCursor) {
  function processItem(err, item) {
    if(item === null) {
      return; // All done!
    }

    externalAsyncFunction(item, function(err) {
      resultCursor.nextObject(processItem);
    });

  }

  resultCursor.nextObject(processItem);
}  

答案 1 :(得分:41)

使用async / await的更现代的方法:

const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
  const doc = await cursor.next();
  // process doc here
}

备注:

  • async iterators到达时,这可能更容易
  • 您可能希望添加try / catch以进行错误检查。
  • 包含的函数应为async,或者代码应包含在(async function() { ... })()中,因为它使用await
  • 如果需要,可以在while循环结束时添加await new Promise(resolve => setTimeout(resolve, 1000));(暂停1秒),以表明它一个接一个地处理文档。

答案 2 :(得分:10)

这适用于使用setImmediate:

的大型数据集
var cursor = collection.find({filter...}).cursor();

cursor.nextObject(function fn(err, item) {
    if (err || !item) return;

    setImmediate(fnAction, item, arg1, arg2, function() {
        cursor.nextObject(fn);
    });
});

function fnAction(item, arg1, arg2, callback) {
    // Here you can do whatever you want to do with your item.
    return callback();
}

答案 3 :(得分:4)

如果有人正在寻找Promise这样做的方式(而不是使用nextObject的回调),那么就是这样。我使用的是Node v4.2.2和mongo驱动程序v2.1.7。这是Cursor.forEach()的asyncSeries版本:

function forEachSeries(cursor, iterator) {
  return new Promise(function(resolve, reject) {
    var count = 0;
    function processDoc(doc) {
      if (doc != null) {
        count++;
        return iterator(doc).then(function() {
          return cursor.next().then(processDoc);
        });
      } else {
        resolve(count);
      }
    }
    cursor.next().then(processDoc);
  });
}

要使用它,请传递游标和对每个文档进行异步操作的迭代器(就像对Cursor.forEach一样)。迭代器需要返回一个promise,就像大多数mongodb本机驱动程序函数一样。

说,您要更新集合test中的所有文档。这就是你要做的事情:

var theDb;
MongoClient.connect(dbUrl).then(function(db) {
  theDb = db;     // save it, we'll need to close the connection when done.
  var cur = db.collection('test').find();

  return forEachSeries(cur, function(doc) {    // this is the iterator
    return db.collection('test').updateOne(
      {_id: doc._id},
      {$set: {updated: true}}       // or whatever else you need to change
    );
    // updateOne returns a promise, if not supplied a callback. Just return it.
  });
})
.then(function(count) {
  console.log("All Done. Processed", count, "records");
  theDb.close();
})

答案 4 :(得分:2)

你可以使用async lib做这样的事情。这里的关键是检查当前doc是否为null。如果是,则表示您已完成。

async.series([
        function (cb) {
            cursor.each(function (err, doc) {
                if (err) {
                    cb(err);
                } else if (doc === null) {
                    cb();
                } else {
                    console.log(doc);
                    array.push(doc);
                }
            });
        }
    ], function (err) {
        callback(err, array);
    });

答案 5 :(得分:0)

你可以在Array中得到结果并使用递归函数进行迭代,就像这样。

myCollection.find({}).toArray(function (err, items) {
    var count = items.length;
    var fn = function () {
        externalAsyncFuntion(items[count], function () {
            count -= 1;
            if (count) fn();
        })
    }

    fn();
});

修改

这仅适用于小型数据集,对于较大的数据集,您应该使用其他答案中提到的游标。

答案 6 :(得分:0)

你可以使用未来:

myCollection.find({}, function(err, resultCursor) {
    resultCursor.count(Meteor.bindEnvironment(function(err,count){
        for(var i=0;i<count;i++)
        {
            var itemFuture=new Future();

            resultCursor.nextObject(function(err,item)){
                itemFuture.result(item);
            }

            var item=itemFuture.wait();
            //do what you want with the item, 
            //and continue with the loop if so

        }
    }));
});

答案 7 :(得分:0)

since node.js v10.3您可以使用异步迭代器

const cursor = db.collection('foo').find({});
for await (const doc of cursor) {
  // do your thing
  // you can even use `await myAsyncOperation()` here
}

Jake Archibald撰写了a great blog post关于异步迭代器的信息,在阅读@ user993683的答案后我才知道。

答案 8 :(得分:-2)

您可以使用简单的setTimeOut&#39; s。这是在nodejs上运行的打字稿中的一个例子(我通过&#39;当&#39;模块使用promises但是也可以在没有它们的情况下完成):

        import mongodb = require("mongodb");

        var dbServer = new mongodb.Server('localhost', 27017, {auto_reconnect: true}, {});
        var db =  new mongodb.Db('myDb', dbServer);

        var util = require('util');
        var when = require('when'); //npm install when

        var dbDefer = when.defer();
        db.open(function() {
            console.log('db opened...');
            dbDefer.resolve(db);
        });

        dbDefer.promise.then(function(db : mongodb.Db){
            db.collection('myCollection', function (error, dataCol){
                if(error) {
                    console.error(error); return;
                }

                var doneReading = when.defer();

                var processOneRecordAsync = function(record) : When.Promise{
                    var result = when.defer();

                    setTimeout (function() {
                        //simulate a variable-length operation
                        console.log(util.inspect(record));
                        result.resolve('record processed');
                    }, Math.random()*5);

                    return result.promise;
                }

                var runCursor = function (cursor : MongoCursor){
                    cursor.next(function(error : any, record : any){
                        if (error){
                            console.log('an error occurred: ' + error);
                            return;
                        }
                        if (record){
                            processOneRecordAsync(record).then(function(r){
                                setTimeout(function() {runCursor(cursor)}, 1);
                            });
                        }
                        else{
                            //cursor up
                            doneReading.resolve('done reading data.');
                        }
                    });
                }

                dataCol.find({}, function(error, cursor : MongoCursor){
                    if (!error)
                    {
                        setTimeout(function() {runCursor(cursor)}, 1);
                    }
                });

                doneReading.promise.then(function(message : string){
                    //message='done reading data'
                    console.log(message);
                });
            });
        });