DEV Community

loading...
Cover image for How to populate nested document in MongoDB.

How to populate nested document in MongoDB.

Rajesh Royal
Designer, Front-end Developer, Traveller, Hooper. I design and code beautifully simple things, and I love what I do.
・1 min read

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.