我想在函数中访问文档中的数据,我处理Item,如何将变量document.date放在itemstring中?
function pagelist(items, res) {
var db = db_login;
result = "<html><body><ul>";
items.forEach(function(item) {
console.log(item)
db.collection('insights').findById(item._id , function(error, document) {
console.log(document)
if (error || !document) {
res.render('error', {});
} else {
**console.log(document.date) //this value is displayed**
}
})
**console.log(document.date)//this value is undefind**
itemstring = "<li>" + item._id + "<ul><li>" + item.textScore +
"</li><li>" + item.created + "</li><li>" + item.document +
"</li></ul></li>";
result = result + itemstring;
});
result = result + "</ul></body></html>";
return result;
}
答案 0 :(得分:0)
当前答案都错过了一个关键点,你的“子”函数是来自asyn函数的回调。它在“父”函数的其余部分之前不会执行。
function pagelist(items, res) {
// ... (1)
items.forEach(function(item) {
db.collection('insights').findById(item._id, function(error, document) {
// this will not execute (4)
});
// before this (2)
});
// or this (3)
// Actual order will be in that of (numbers)
return result;
}
您唯一的选择是使父函数的行为与db函数的行为相同。即也让它asyn。
function pagelist(items, done) { // <= "done"
items.forEach(function(item) {
db.collection('insights').findById(item._id, function(error, document) {
// Now you can call done with document that is available here
done(document); // or done(document.date); w/e
});
// return result; // Returns are useless* in asyncs
}
无论你在哪里打电话给pagelist()
传递回调函数“完成”并在那里做东西
app.use(function(req, res){
pagelist(items, function(document){ // <= this will be the "done" function
var itemstring = document.date;
// do whatever you want with the document here.
res.render(~);
console.log(document.date);
});
});
答案 1 :(得分:-1)
试试这个:
将局部变量document
分配给全局变量doc
并在函数外部访问它;
function pagelist(items, res) {
var db = db_login;
var doc;
result = "<html><body><ul>";
items.forEach(function(item) {
console.log(item)
db.collection('insights').findById(item._id , function(error, document) {
console.log(document)
doc=document; // assignment of the local variable to global variable
if (error || !document) {
res.render('error', {});
} else {
console.log(document.date)
}})
console.log(doc.date) // here is use of global variable
itemstring = "<li>" + item._id + "<ul><li>" + item.textScore +
"</li><li>" + item.created + "</li><li>" + item.document +
"</li></ul></li>";
result = result + itemstring;
});
result = result + "</ul></body></html>";
return result;
}
享受:)