1.下面的函数应以数组形式返回集合报告中的所有文档。
function listdocs(){
var valuess=[];
MongoClient.connectAsync(murl).then(function(db) {
return db.collection('reports').find({}).toArrayAsync();
}).then(function(reports) {
valuess=reports;
}).catch(function(err) {
console.log(err);
});
return valuess;
}
最佳答案
正如您所知,在 Node.js 中一切都是异步的,因此如果您调用 listdocs()
它甚至会在 MongoClient.connectAsync
返回之前返回。因此,您需要更改 listdocs
以接受在获取结果时调用的回调。
代码应如下所示:
function listdocs(callback) {
MongoClient.connectAsync(murl).then(function(db) {
return db.collection('reports').find({}).toArrayAsync();
}).then(function(reports) {
callback(null, reports)
}).catch(function(err) {
callback(err, null);
});
}
之后您可以像这样调用该函数:
listdocs(function(err, data) {
if (err) {
// do something with the error
}
// do something with the result
});
关于node.js - 如何使此函数返回数组中集合中所有文档的列表。我正在使用 mongodb 和 bluebird 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269890/