【发布时间】:2017-02-12 08:40:48
【问题描述】:
在 node.js 服务器上工作,从我的 mongoDB 数据库中检索数据,但它变得有点笨拙,我想使用 Promise 主要是因为我以前从未使用过它们,并且希望获得洞察力,还想清理代码。我正在使用节点中的bluebird 模块来promisify mongodb,目前可以查看一项。
var client = MongoClient.connectAsync('mongodb://localhost:27017/stockData')
.then(function(db) {
return db.collection("stockData").findOneAsync({ High: 253.41796296683228 })
})
.then(function(doc) {
console.log(doc)
})
.catch(function(err) {
console.log(err)
});
但是我希望能够使用光标循环浏览多个文档,但是我无法将整个事情都包裹起来,并且想在此处转换这段代码以使用 Promise。
MongoClient.connect(url, function(err,db){ //set up connection to mongodb takes two parameters a url for the db and a callback function
assert.equal(err,null) //check to see if there any errors connecting to the database
var cursor = db.collection('stockData').find().limit(10) // cursor will be an array of objects retrieved from the database
cursor.forEach(function(doc, err){ //loop through the cursor
assert.equal(null,err) //check for errors
console.log(doc)
}, function(){
db.close(); //close the database once the query is finished
});
});
如果您能解释发生的事情以便我能很好地处理它,我们将不胜感激。
【问题讨论】: