简体   繁体   中英

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

I head and always read that MongoDB driver (>2.0) for NodeJS supports promises. But the only examples I find are with the connect() and findOne() functions. While it works for those and I can get promises, it doesn't with aggregate() nor with 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.

Chain the result from find() or aggregate() to .toArray() . The documentation of toArray for the current mongodb nodejs driver is here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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