samman adhikari
samman adhikari

Reputation: 651

How to populate a field inside a embedded document in mongoose?

I have a model "Post" that is something like this

{
   // Some other fields
   comments: [
    new mongoose.Schema({
      content: {
        type: String,
        required: [true, "Content for a comment is required."],
      },
      author: {
        type: mongoose.Types.ObjectId,
        ref: "User",
        required: [true, "Author for a comment is required."],
      },
    }),
}

I cannot figure out a way to populate the author field inside comment after fetching posts. How may I do so?

Upvotes: 1

Views: 525

Answers (1)

Try Populating across multiple levels

Post.find({ }).populate({
    path: 'comments',
    populate: { path: 'author' }
});

Upvotes: 1

Related Questions