Categories
JavaScript Answers

How to populate nested array in Mongoose?

Spread the love

Sometimes, we want to populate nested array in Mongoose.

In this article, we’ll look at how to populate nested array in Mongoose.

How to populate nested array in Mongoose?

To populate nested array in Mongoose, we can use the populate method.

For instance, we write

Project.find(query)
  .populate({
    path: 'pages',
    populate: {
      path: 'components',
      model: 'Component'
    }
  })
  .exec((err, docs) => {});

to call populate with an object with the array property we want to populate in the docs result.

We populate pages with the components entries in the returned Project entries.

docs has the returned result with the nested array results inside each entry.

Conclusion

To populate nested array in Mongoose, we can use the populate method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *