聚合游标
AggregationCursor()AggregationCursor.prototype.addCursorFlag()AggregationCursor.prototype.close()AggregationCursor.prototype.eachAsync()AggregationCursor.prototype.map()AggregationCursor.prototype.next()AggregationCursor.prototype[Symbol.asyncIterator]()
AggregationCursor()
参数
agg«Aggregate»
继承
聚合游标是用于一次处理一个聚合结果的并发原语。它类似于 QueryCursor。
聚合游标除了几种其他机制之外,还实现了 Node.js streams3 API,用于一次从 MongoDB 加载一个文档。
创建聚合游标会执行模型的预聚合钩子,但不会执行模型的后期聚合钩子。
除非你是高级用户,否则不要直接实例化此类。使用 Aggregate#cursor() 代替。
AggregationCursor.prototype.addCursorFlag()
参数
flag«String»value«Boolean»
返回
- «AggregationCursor» this
添加 游标标志。对于设置 noCursorTimeout 和 tailable 标志很有用。
AggregationCursor.prototype.close()
参数
callback«Function»
返回
- «Promise»
见
将此游标标记为已关闭。将停止流式传输,后续对 next() 的调用将出错。
AggregationCursor.prototype.eachAsync()
参数
fn«Function»[options]«Object»[options.parallel]«Number» 并发执行的 promise 数量。默认为 1。[options.batchSize=null]«Number» 如果设置,Mongoose 将使用最多batchSize个文档的数组调用fn,而不是单个文档[options.continueOnError=false]«Boolean» 如果为 true,eachAsync()会遍历所有文档,即使fn抛出错误。如果为 false,eachAsync()会立即抛出错误,如果给定函数fn()抛出错误。
返回
- «Promise»
对游标中的每个文档执行 fn。如果 fn 返回一个 promise,则会等待 promise 解决,然后继续迭代下一个。返回一个在完成后解决的 promise。
AggregationCursor.prototype.map()
参数
fn«Function»
返回
- «AggregationCursor»
注册一个转换函数,该函数随后会映射通过流式接口或 .next() 检索到的文档
示例
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
const cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
}); AggregationCursor.prototype.next()
返回
- «Promise»
从此游标获取下一个文档。如果不再有文档,将返回 null。
AggregationCursor.prototype[Symbol.asyncIterator]()
返回一个用于 for/await/of 循环 的异步迭代器。您无需显式调用此函数,JavaScript 运行时将为您调用它。
示例
// Async iterator without explicitly calling `cursor()`. Mongoose still
// creates an AggregationCursor instance internally.
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}
// You can also use an AggregationCursor instance for async iteration
const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor();
for await (const doc of cursor) {
console.log(doc.name);
}Node.js 10.x 本机支持异步迭代器,无需任何标志。您可以使用 --harmony_async_iteration 标志 在 Node.js 8.x 中启用异步迭代器。
注意:如果 Symbol.asyncIterator 未定义,则不会设置此函数。如果 Symbol.asyncIterator 未定义,则意味着您的 Node.js 版本不支持异步迭代器。

