【问题标题】:Mongoose aggregate cursor promiseMongoose 聚合游标承诺
【发布时间】:2018-02-05 07:08:47
【问题描述】:

我正在尝试聚合一个大型数据集,因此我将游标与聚合一起使用。但是,我找不到有关如何在不使用附加延迟的情况下实现此功能的文档。我觉得必须有一种方法可以将aggregate().cursor().each() 与聚合完成后解决的承诺结合起来。有人知道怎么做吗?

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

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;

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    我发现这个 SO 正在寻找有关使用带有承诺的聚合游标的一般帮助。经过大量的试验和错误,如果其他人偶然发现这一点,我发现游标对象有一个 next() 方法可以返回一个承诺,就像其他游标一样。但是,出于某种原因,如果没有 async 标志,我无法获得对它的引用。因此,如果您使用的是蓝鸟:

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

    Mongoose 5 更新

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

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

    【讨论】:

    • 我可能误读了,但我认为在第一个代码示例的 while 块中有一个额外的开放括号 (? ` while ((doc = yield cursor.next()) { console.log(doc._id) } `
    • 谢谢...它实际上是一个缺少的结束括号
    • 如果您想对每个文档进行异步更新,这无济于事,还是我遗漏了什么?
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 2015-02-25
    • 2017-10-13
    • 2019-10-21
    • 1970-01-01
    • 2019-05-28
    • 2017-12-08
    • 2020-10-04
    相关资源
    最近更新 更多