猫鼬聚合光标承诺 [英] Mongoose aggregate cursor promise

查看:77
本文介绍了猫鼬聚合光标承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试汇总大型数据集,因此我将光标与汇总一起使用.但是,在不使用其他延迟的情况下,我找不到有关如何实现此目的的文档.我觉得必须有一种方法将aggregate().cursor().each()与一个在合并完成后已解决的承诺相结合.有人知道该怎么做吗?

I am trying to aggregate a large data set so I am using a cursor along with aggregate. However, I cannot find documentation on how to implement this without using an additional deferred. I feel there has to be a way to combine aggregate().cursor().each() with a promise that is resolved after aggregation is finished. Does anyone know how to do this?

此代码有效,并且基于 http://mongoosejs.com/docs/api .html#aggregate_Aggregate-cursor 我正在尝试找到一种无需额外承诺就可以做到这一点的方法.

This code works and is based on http://mongoosejs.com/docs/api.html#aggregate_Aggregate-cursor I am trying to find a way to do this without the additional promise.

aggregation = MyModel.aggregate().group({
  _id: '$name'
});

deferred = Q.defer();

aggregation.cursor({
  batchSize: 1000
}).exec().each(function(err, doc) {
  if (err) {
    return deferred.reject(err);
  }
  if (!doc) {
    return deferred.resolve(); // done
  }
  // do stuff with doc
});
return deferred.promise;

推荐答案

我找到了该SO,希望在使用带有promise的聚合游标时寻求一般帮助.经过大量的试验和错误,并且如果其他人迷失了这一点,我发现游标对象具有一个next()方法,该方法像其他游标一样返回一个Promise.但是由于某种原因,如果没有async标志,我将无法获得对它的引用.因此,如果您使用的是bluebird:

I found this SO looking for general help on using the aggregation cursor with promises. After a lot of trial and error and if anyone else stumbles on this, I found that the cursor object has a next() method that returns a promise, like other cursors. For some reason, I couldn't get a reference to it without the async flag, though. So if you're using bluebird:

let bluebird = require("bluebird");
let aggregation = MyModel.aggregate().group({
  _id: '$name'
});

aggregation.cursor({
  batchSize: 1000,
  async: true
}).exec().then(cursor => {
  return bluebird.coroutine(function* () {
    let doc;
    while ((doc = yield cursor.next())) {
      console.log(doc._id)
    }
  })()
}).then(() => { console.log("done with cursor"); })

猫鼬5更新

exec()调用不再返回承诺,仅返回游标本身,并且不再需要async: true属性.

Update for Mongoose 5

The exec() call no longer returns a promise, just the cursor itself, and the async: true property is no longer necessary.

let aggregation = MyModel.aggregate().group({
  _id: '$name'
});

(async function () {
  let doc, cursor;
  cursor = aggregation.cursor({batchSize: 1000}).exec();

  while ((doc = await cursor.next())) {
    console.log(doc._id)
  }
})()
.then(() => console.log("done with cursor"); )

这篇关于猫鼬聚合光标承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆