Mongoose заполняется, если findById (); не заполняется, если find () - PullRequest
0 голосов
/ 11 января 2019

По сути, Mongoose заполняет массив, если я использую 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 () не работает.)

1 Ответ

0 голосов
/ 11 января 2019
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 ()

...