【问题标题】:Mongoose populates if findById(); does not populate if find()猫鼬填充 if findById();如果 find() 不填充
【发布时间】: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


【解决方案1】:
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()

【讨论】:

  • 现在尝试回答我认为这应该告诉你出了什么问题
  • 谢谢,它会打印出 foundUser 和朋友。但是后来在代码中,尝试渲染时,视图中未定义朋友。 (此外,使用 findById().populate() 时,console.log(foundUser.friends) 可以工作(即不是未定义的)......很奇怪。
  • 而不是 findById() 尝试使用 findOne()
  • find() 给出了一个数组,因此当链 populate() 时,它引用使用前一个方法找到的对象(找到的对象)。所以 findOne() 和 findById() 给你一个对象,而 find() 给你一个数组,所以 populate() 在使用 find() 但不使用 findById() 和 findOne() 时会崩溃
  • 当 findOne().populate() 或 findById().populate() - 你得到 {}.populate() 但 find().populate() - 你得到 [] 时是这样的。 populate() ...这就是原因..希望这有帮助..干杯
猜你喜欢
  • 2015-07-13
  • 2016-10-10
  • 2015-07-13
  • 2020-01-17
  • 2015-08-26
  • 2021-05-06
  • 2019-09-16
  • 2021-05-03
相关资源
最近更新 更多