基本上,如果我使用 findById() .populate(),猫鼬似乎会填充一个数组,但是如果我使用 find() .populate(),则不是。我需要使用findById()...
有什么想法为什么find()。populate()似乎不起作用?
代码段(快递路线):
//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()无法正常工作。)
答案 0 :(得分:0)
console.log("! My friends: " + foundUser.friends);
//Is Undefined if using find()... but NOT if using findById(). Weird.
这是使用find()时发生的情况,它为您和对象数组提供的不是单个对象,因此您不能使用foundUser.friends ..而是尝试
console.log("! My friends: " + foundUser); // here it will give results
这就是为什么无论使用find()还是findById()都包含视图的原因