Search code examples
node.jsmongoosemongoose-populate

How to populate an object inside an object in an array?


I am currently working on a project with mongoose, and I have been stuck in a problem with the mongoose populate() method.

The problem is that I cannot populate an object inside an object in an array.

// * I simplified the code below.

// Profile Document
Profile = model('Profile', new Schema({
    _user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    posts: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Post',
        // Post = { 
        //   _id: Number,
        //   _poster: { 
        //     type: Schema.Types.ObjectId,
        //     ref: 'User',
        //   }
        // };
      },
    ],
}));

// app.js
 const profile = await Profile.findOne({ _user: userId })
    .populate('_user')  // it works
    .populate('posts')  // it works too
    .populate('posts._poster'); // it doesn't work

Is there any way to populate a nested object in an array?

It'd be great if you could answer my question. Thank you in advance.



I tried accessing the notation properly to populate *_poster*, however, it didn't still work. The code is below.

    const profile = await Profile.findOne({ _user: userId })
      .populate('_user')
      .populate('posts');

    await profile.toObject();
    profile.posts.forEach((post) => {
      profile.populate('posts.post._poster');
    })


Solution

  • I have tested your schema this works great, could you test and let me know

    const profile = await Profile.findOne({
            _id: '5f108ed7ecc4881a6c35e27b',
        })
            .populate('_user')
            .populate({
                path: 'posts',
                populate: {
                    path: '_poster',
                    model: 'User',
                },
            })
            .exec();
        console.log(profile);