Mongo的Cursor.nextObject有时错误返回空?

我将async.queueCursor.nextObject结合起来,遍历游标并对返回的文档进行一些asynchronous的工作。

有一个很好的小包,已经这样做, https://www.npmjs.org/package/mongo-cursor-processing ,但不幸的是不公开底层队列,我需要。

所以,我尝试着自己实施,但遇到了一些麻烦。 有时, Cursor.nextObject实际上有更多的文档时返回null

下面是一些我已经附加到队列中的代码片段来说明:

 if (this.cursor && this.length() < this.concurrency) { this.cursor.nextObject(function(err, item) { console.log(this.name + ': ' + (item ? item._id : '<null>') + ' ' + (err ? err : '<null>')); if (item) { this.push(item); } else { // delete this.cursor; } }.bind(this)); } 

控制台日志显示:

 ... Maybe 100 lines ... prop-queue: 511abbd59c0d972a3e000119 <none> prop-queue: 511abbd59c0d972a3e00011d <none> prop-queue: 511abbd59c0d972a3e000120 <none> prop-queue: 511abbd59c0d972a3e000122 <none> prop-queue: <none> <none> prop-queue: 511abbd59c0d972a3e000125 <none> prop-queue: 511abbd59c0d972a3e000127 <none> prop-queue: 511abbd59c0d972a3e000129 <none> prop-queue: 511abbd59c0d972a3e00012c <none> ... 1000's more lines before the next null ... 

有时,在下一次调用成功之前, <none> <none>行会重复两次。

真正有趣的部分是当我在Mongo shell中执行查询时,在511abbd59c0d972a3e000122511abbd59c0d972a3e000125被打印到控制台之间有一个暂停。 暂停时间大约为0.75秒,正好在光标所在的位置。 我在查询中迭代了数千个文档,这是我经历的唯一的停顿。 此外,审查空白两面的两个文件没有显示出任何特殊性。

任何想法可能导致两个可能相关的现象?

我还不确定是什么原因造成的,但似乎是罪魁祸首。

在暂停期间, Cursor.nextObject在第一次返回之前被调用了几次。 其中一些调用返回null 。 解决scheme是确保Cursor.nextObject不会被同时调用。

 if (this.cursor && !this.cursor_exec && this.length() < this.concurrency) { this.cursor_exec = true; this.cursor.nextObject(function(err, item) { console.log(this.name + ': ' + (item ? item._id : null) + ' ' + (err ? err : null)); this.cursor_exec = false; if (item) { this.push(item); } else { delete this.cursor; } }.bind(this)); }