Using native ES6 promises with MongoDB

后端 未结 2 1692
天命终不由人
天命终不由人 2021-01-02 21:02

I\'m aware that the Node driver for Mongo can be promisified using external libraries. I was curious to see if ES6 promises could be used with MongoClient.connect

2条回答
  •  伪装坚强ぢ
    2021-01-02 22:09

    There is nothing to get around, this is the expected behavior. cursor.count() returns a promise, if you want the value, you need to use .then, e.g.

    DbConnection({}).then(
     db => {
        let cursor = db.collection('bar').find();
        return cursor.count();
      }
    }).then(
      count => {
        console.log(count);
      },
      err => {
        console.log(err);
      }
    );
    

    or simplified

    DbConnection({}).then(db => db.collection('bar').find().count()).then(
      count => console.log(count),
      err => console.log(err)
    );
    

提交回复
热议问题