简体   繁体   English

来自aggregate()和find()的MongoDB驱动程序用于NodeJS

[英]Promise from aggregate() and find() with MongoDB driver for NodeJS

I head and always read that MongoDB driver (>2.0) for NodeJS supports promises. 我总是读到NodeJS的MongoDB驱动程序(> 2.0)支持promises。 But the only examples I find are with the connect() and findOne() functions. 但我找到的唯一例子是connect()和findOne()函数。 While it works for those and I can get promises, it doesn't with aggregate() nor with find(). 虽然它适用于那些,我可以得到承诺,它不与aggregate()或find()。 I get that's because they might be returning cursors, but since there is promise support, where are those promises? 我得到那个是因为他们可能会返回游标,但是因为有承诺支持,这些承诺在哪里? There must be a way to work with them. 必须有办法与他们合作。 A link, an example or simple explanation would be so welcome :) 一个链接,一个例子或简单的解释将是如此受欢迎:)

Thank you, Jordy. 谢谢Jordy。

Chain the result from find() or aggregate() to .toArray() . 将结果从find()aggregate().toArray() The documentation of toArray for the current mongodb nodejs driver is here . 当前mongodb nodejs驱动程序的toArray文档在这里

What you can do is write your own custom promise function such as: 您可以做的是编写自己的自定义承诺函数,例如:

Query.prototype.find = function (callback) {
  return new Promise((resolve, reject) => {
    this.model.find(this.query).skip(this.skip).limit(this.limit).sort(this.sort).exec((err, results) => {
        if (err) {
            return reject(err);
        }

        return resolve({ find: results });
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM