DEV Community

Cover image for How to populate nested document in MongoDB.
Rajesh Royal
Rajesh Royal

Posted on

How to populate nested document in MongoDB.

Recently I run into a situation where I needed to fetch nested mongodb document data and wasted my 1 hour. If you are facing the same this is for you.

Here is the stackoverflow - Populate nested array in mongoose

I used this query -

public courseListRead(): Promise<ICourse[]> {
    return this.courseModel.find().sort({
      index: 1
    }).populate('instructor').populate({
      path: 'categories',
      populate: {
        path: 'posts',
        model: 'CourseCategoryPost'
      }
    }).exec();
  }
Enter fullscreen mode Exit fullscreen mode

To populate nested documents you have to use .populate() method like above.

I'm very beginner at MongoDB.

Thanks.

Discussion (1)

Collapse
maprangsoft profile image
Maprangsoft

thank you.