Using native ES6 promises with MongoDB

后端 未结 2 1693
天命终不由人
天命终不由人 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 21:54

    Another syntax for the response of loganfsmyth (thanks by the way)

    cursor.count().then(function(cursor_count){
      if(cursor_count){
        // use cursor
      }else{
        // no results
      }
    }
    
    0 讨论(0)
  • 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)
    );
    
    0 讨论(0)
提交回复
热议问题