1

These are my data models:

    var campSchema = new mongoose.Schema({
   image : String,
   description : String,
   comment: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
   ],
   feeds : [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Feed"
      }
   ]
});

and :

    var feedSchema = new mongoose.Schema({
    text : String,
    createdAt: { type: Date, default: Date.now },
    author : {
        id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
        },
        username: String
    },
    comment: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
  ]
});

and here is my nodejs request which doesn't populate the comments into my template :

app.get("/feeds", isLoggedIn, function(req, res) {
    console.log(req.user);
    Camp.find({}).populate("feeds").populate("feeds.comment").exec(function(err, myCamp){
        if(err){
            console.log(err);
        } else {
            myCamp.forEach(function(camp){
                if(camp.address === req.user.address){ 
                        console.log(building);
                         res.render("feeds/feeds", {building : building});
                }
            });
        }
    });
});

which does't work! I want to populate comments from Feeds data model in to my template. i will be so grateful if someone could help, thank you.

Farbod
  • 25
  • 3
  • Hello, Plz check link 1) https://stackoverflow.com/questions/28179720/mongoose-populate-nested-array. 2) https://stackoverflow.com/questions/19222520/populate-nested-array-in-mongoose. Mongoose 4.5 and above support ... – IftekharDani Jan 15 '18 at 05:19

1 Answers1

1

You should change the code to

.populate({
            path: 'feeds',
            model: 'Feed',
            populate: {
                path: 'comment',
                model: 'Comment'
            }
        })

It would be a better idea to use the mongoose-deep-populate Plugin which helps you do it with ease.

deepak thomas
  • 1,118
  • 9
  • 23