使用MongoDB的本机ES6承诺

Ric*_*her 6 javascript mongodb node.js es6-promise babeljs

我知道可以使用外部库来宣传 Mongo的Node驱动程序.我很想知道是否可以使用ES6承诺MongoClient.connect,所以我尝试了这个(使用Babel 5.8.23进行转换):

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);
  }
);
Run Code Online (Sandbox Code Playgroud)

输出是{Promise <pending>}.与游标有关的任何事情似乎都会产生类似的结果.有没有办法解决这个问题,还是我完全咆哮错误的树?

编辑:节点版本4.1.0.

log*_*yth 10

没有什么可以解决的,这是预期的行为.cursor.count()返回一个promise,如果你想要这个值,你需要使用.then,例如

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

或简化

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

  • IME,不需要`err => {console.log(错误)` - 只需将`console.log`放在`.then`错误参数中 (2认同)