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?