简体   繁体   English

使用MongoDB的本机ES6承诺

[英]Using native ES6 promises with MongoDB

I'm aware that the Node driver for Mongo can be promisified using external libraries. 我知道可以使用外部库来宣传 Mongo的Node驱动程序。 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): 我很想知道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);
  }
);

The output is {Promise <pending>} . 输出为{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. 编辑:节点版本4.1.0。

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 , eg 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);
  }
);

or simplified 或简化

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

Another syntax for the response of loganfsmyth (thanks by the way) loganfsmyth响应的另一种语法(顺便说一下)

cursor.count().then(function(cursor_count){
  if(cursor_count){
    // use cursor
  }else{
    // no results
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM