MongoDB : does Collection.Find() support promise

Viewed 4850

I was trying to revamp an old Nodejs web service to replace callback functions with chained promises. When querying mongodb we used the syntax below to iterate through a result set.

collection.find(filter).toArray(function(err, items) {
          if (err) {
            throw(err);
          } else {
            console.log(items);

          }       

If I try to replace the .toArray() section with a .then() I get the below error "col.find(...).then is not a function".

If I replace .find() with .findOne().then(), the code works perfectly.

Any help is appreciated.

2 Answers

find returns a Cursor, but the cursor's toArray method returns a promise. So you can do:

collection.find(filter).toArray().then(...)

I assume you're using mongoosejs.

collection.find() is just a query. To cause it to execute and return a promise, you need to call .exec() on it.:

collection.find(filter).exec()
    .then(items => console.log(items))
    .catch(err => { // handle error })

The mongoose docs give you more details on how to use mongoose with either callbacks or promises: https://mongoosejs.com/docs/api.html#model_Model.find

Related