使用MongoDB的本机ES6承诺 [英] Using native ES6 promises with MongoDB
问题描述
我知道Mongo的Node驱动程序可以 promisified 使用外部库。我很想知道ES6承诺是否可以与 MongoClient.connect
一起使用,所以我尝试了这个(使用Babel 5.8.23进行转换):
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);
}
);
输出 {Promise< pending>}
。与游标有关的任何事情似乎都会产生类似的结果。有没有办法解决这个问题,还是我完全咆哮错误的树?
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?
编辑:节点版本4.1.0。
node version 4.1.0.
推荐答案
没有什么可以解决的,这是预期的行为。 cursor.count()
返回一个承诺,如果你想要这个值,你需要使用 .then
,例如
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);
}
);
或简化
DbConnection({}).then(db => db.collection('bar').find().count()).then(
count => console.log(count),
err => console.log(err)
);
这篇关于使用MongoDB的本机ES6承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!