我正在尝试从此函数返回数据。 Console.log(文档)成功显示控制台中的数据。但这只适用于函数体。我无法将此数据返回到模板。我该怎么办?我应该为node.js使用一些异步包,还是可以这样完成?
谢谢。
var projects = req.user.projects;
var docs = [];
db.collection('documents', function(err, collection) {
for (i = 0; i < projects.length; i++) {
collection.find({'_projectDn': projects[i].dn},function(err, cursor) {
cursor.each(function(err, documents) {
if(documents != null){
console.log(documents);
//or docs += documents;
}
});
});
}
});
console.log(documents); // undefined
res.render('projects.handlebars', {
user : req.user,
documents: docs
});
答案 0 :(得分:4)
这些db函数是异步的,这意味着当你尝试记录它时,该函数还没有完成。您可以使用callback进行记录,例如:
function getDocuments(callback) {
db.collection('documents', function(err, collection) {
for (i = 0; i < projects.length; i++) {
collection.find({
'_projectDn': projects[i].dn
}, function(err, cursor) {
cursor.each(function(err, documents) {
if (documents !== null) {
console.log(documents);
callback(documents);// run the function given in the callback argument
}
});
});
}
});
}
//use the function passing another function as argument
getDocuments(function(documents) {
console.log('Documents: ' + documents);
});