【发布时间】:2019-06-05 23:10:40
【问题描述】:
基本上,如果我使用 findById().populate(),Mongoose 似乎会填充一个数组,但如果我使用 find().populate() 则不会。我需要使用 findById()...
任何想法为什么 find().populate() 似乎不起作用?
代码sn-p(快线):
//Retrieve a user's details, including their friends, for displaying.
app.get("/friends", function(req, res){
//People.find({name: 'Tom'}).populate("friends").exec(function(err, foundUser){
People.findById("5c37f2d67c8").populate("friends").exec(function(err, foundUser){
console.log("! My friends: " + foundUser.friends); //Is Undefined if using find()... but NOT if using findById(). Weird.
if(err){
console.log(err);
res.redirect("/");
} else {
//res.send(foundUser); //When I pass foundUser to the View, foundUser.friends is ALWAYS populated / never undefined, regardless of using find() or findUser(). Weird, as the above console.log() is undefined if using find().
res.render("peopleIndex", {foundUser: foundUser});
}
});
});
编辑:解决方案:如果有人想知道,您可以使用 findOne() 而不是 find() 来填充以传递给视图。 (仍然不确定为什么 find() 不起作用。)
【问题讨论】:
-
身份证无效,是的,我知道。假设它有效;我在发布时缩短/编辑了它。
-
使用 findOne() 代替 find() 解决。
-
尝试在 populate 中使用单引号。即 .populate('friends') 希望它有效。
标签: javascript mongodb express mongoose mongoose-populate