本文介绍了依次遍历mongodb游标(在等待回调之前,移至下一个文档)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using mongoskin, I can do a query like this, which will return a cursor:

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

      }
}

但是,我想为每个文档调用一些异步函数,并且仅在回调后再移动到光标的下一个项目(类似于async.js模块中的eachSeries结构).例如:

However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called back (similar to the eachSeries structure in the async.js module). 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(),因为这是一个大批量操作,并且结果可能一次也无法存储在内存中.

I don't wan't to use toArray() as this is a large batch operation, and the results might not fit in memory in one go.

推荐答案

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

If you don't want to load all of the results into memory using toArray, you can iterate using the cursor with something like the following.

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);
}

这篇关于依次遍历mongodb游标(在等待回调之前,移至下一个文档)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:38