Using native ES6 promises with MongoDB

六眼飞鱼酱① 提交于 2019-11-30 15:37:06

问题


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, so I tried this (using Babel 5.8.23 to transpile):

import MongoClient from 'mongodb';

function DbConnection({
  host = 'localhost',
  port = 27017,
  database = 'foo'
}) {
  return new Promise((resolve, reject) => {
    MongoClient.connect(`mongodb://${host}:${port}/${database}`, 
    (err, db) => {
      err ? reject(err) : resolve(db);
    });
  });
}

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

The output is {Promise <pending>}. Anything to do with cursors seems to yield a similar result. Is there a way to get around this or am I barking up the wrong tree entirely?

Edit: node version 4.1.0.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/32792163/using-native-es6-promises-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!