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;
}
答案 0 :(得分:0)
正如您在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
});