Anton Shuvalov Anton Shuvalov - 27 days ago 25
Node.js Question

Populate nested array in mongoose

How can I populate "components" in the example document:

{
"__v": 1,
"_id": "5252875356f64d6d28000001",
"pages": [
{
"__v": 1,
"_id": "5252875a56f64d6d28000002",
"page": {
"components": [
"525287a01877a68528000001"
]
}
}
],
"author": "Book Author",
"title": "Book Title"
}


This is my JS where I get document by Mongoose:

Project.findById(id).populate('pages').exec(function(err, project) {
res.json(project);
});

Answer

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

Comments