0

I'm writing a forum module using Mongoose & Nodejs.

I have a collection of ForumPost objects which have a property "comments" which is a mongoose schema containing a reference property "author", which references a User model. I'm having trouble populating the "author" property for each of the items in the "comments" array.

Here's the ForumPost object definition:

var ForumPost = db.model("ForumPost", {

    author: { type: Schema.Types.ObjectId, ref: "User", required: true, default: null, select: true},

    comments: [new db.Schema({
        author: { type: Schema.Types.ObjectId, ref: "User" },
        comment: { type: String, default: ""},

    })]

});

When I pull these from the database, i'm populating the "author" field of the forum post, which works fine as it's a basic populate operation.

I've been trying to populate the "author" field of the comments array this morning to no avail, my latest attempt is posted below.

I use the following query:

ForumPost.findOne({alliance_id: alliance._id, _id: post_id})
                        .populate("author")
                        .populate({ 
                             path: 'comments',
                             populate: {
                               path: 'comments.author',
                               model: 'User'
                             } 
                          })
                        .select("comments")
                        .exec(function(error, post) {

                return res.json(post);
            });

Is this possible to populate the "author" field of the objects in the comments array of ForumPost in this single query?

Lee Brindley
  • 6,242
  • 5
  • 41
  • 62
  • http://stackoverflow.com/questions/24358630/populate-ref-nested-in-object-array – Sunil B N Dec 28 '15 at 11:24
  • That answer applied to this question would mean (I think) that i'd have to pull the ForumPost objects, then loop through the objects in the comments array and fetch them manually. I'm looking to see if it's possible to do it in the same query. I've edited the question to make this clearer – Lee Brindley Dec 28 '15 at 11:28
  • try this http://stackoverflow.com/questions/10568281/mongoose-using-populate-on-an-array-of-objectid it is possible you will have to register comments as a schema for this to work. – Muli Yulzary Dec 28 '15 at 14:38

1 Answers1

0

Because you're not doing any nested population, you can include both paths in a single populate call:

ForumPost.findOne({alliance_id: alliance._id, _id: post_id})
    .populate('author comments.author')
    .select('author comments')
    .exec(function(error, post) {
        return res.json(post);
    });
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471