有人可以向我解释为什么,当我执行以下代码时,我会得到一个空列表?
Post.find({ "emailPublisher": req.body.emailUser }, { _id: 0, "idPost": 1 }, function (err, idsposts) {
console.log(idsposts)
for (i in idsposts) { list.push(idsposts[i].idPost) }
});
console.log("list is " + list);
看起来像这一行:
console.log("list is " + list);
在查找查询之前发生。
答案 0 :(得分:1)
您需要将其插入回调中:
Post.find({ "emailPublisher": req.body.emailUser }, { _id: 0, "idPost": 1 }, function (err, idsposts) {
console.log(idsposts)
for (i in idsposts) { list.push(idsposts[i].idPost) }
console.log("list is " + list);
});
find是一个异步操作。
答案 1 :(得分:0)
那么为什么这个查询不起作用?
Like.aggregate({ $group: { _id: "$idPost", totalNumLikes: { $sum: 1 } } }, function (err, likesResult) {
if (err) {
console.log("error in app.post(numlikesforUser)")
return res.send(err);
}
Post.find({idPost: {$in: likesResult.map(r => r._id)}, "emailPublisher": req.body.emailUser }, function (err, posts) {
for (var i =0; i < likesResult.length; i++) {
var result = likesResult[i];
var post = posts.filter(p => p._id === result._id)[0];
if (post != null) {
likesCount = likesCount + result.totalNumLikes
}
}
console.log("likescount is:::::::::::::" + likesCount);
});
});