TigrouMeow
TigrouMeow

Reputation: 3779

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.

Upvotes: 4

Views: 5469

Answers (2)

Rico Chen
Rico Chen

Reputation: 2298

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

Upvotes: 13

Ayush Mittal
Ayush Mittal

Reputation: 559

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

Upvotes: 0

Related Questions