I'm attempting to retrieve a structure where I first populate content
, and within content
there is an array field named comments
. From comments
, I aim to populate user
.
Below is the schema:
const contentScheme = new Schema({
post_id: { type: Number },
post_type: { type: String },
likes_count: { type: String },
likes_by: [{type: Schema.Types.ObjectId, ref: 'User'}],
comments_count:{ type: Number },
comments:[{type: Schema.Types.ObjectId, ref: 'Comment'}],
},{timestamps : true});
const commentScheme = new Schema({
created_by: { type: Schema.Types.ObjectId, ref: 'User' },
post_id: { type: String },
post_type: { type: String },
comment: { type: String },
reply_to: { type: Number },
pinned:{ type: Number },
},{timestamps : true});
const userSchema = new Schema({
email: { type: String, required: true, index: { unique: true } },
avatar: { type: String },
token: { type: String },
display_name: { type: String , required: true},
last_updated: {
type: Date,
default: Date.now
}
});
Here is my current approach:
ContentModel.findOne({
post_id:args.post_id,post_type:args.post_type},(err,rslt)=>{
if(err){
reject(err);
}
else {
console.log(rslt)
resolve(rslt);
}
}).populate("comments").populate({ path: 'comments.created_by', model: UserModel })
Here is the result from the above query:
{
_id: new ObjectId("618cdecbf1551c02355e4e6a"),
post_id: 1,
post_type: 'note',
likes_count: '1',
likes_by: [
new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
new ObjectId("6187bed3e4d3a0aa98fd0cc9")
],
comments_count: 4,
comments: [
{
_id: new ObjectId("618dced6ee441fca8e4e1659"),
created_by: new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
post_id: '1',
post_type: 'note',
comment: 'INI COMMENT',
reply_to: null,
pinned: 0,
replies: [],
createdAt: 2021-11-12T02:17:58.464Z,
updatedAt: 2021-11-12T02:17:58.464Z,
__v: 0
},
{
_id: new ObjectId("618dd2281c5f1ddc6589728d"),
created_by: new ObjectId("6187bed3e4d3a0aa98fd0cc9"),
post_id: '1',
post_type: 'note',
comment: 'TEST COMMENT MEMBER',
reply_to: null,
pinned: 0,
replies: [],
createdAt: 2021-11-12T02:32:08.092Z,
updatedAt: 2021-11-12T02:32:08.092Z,
__v: 0
}
],
createdAt: 2021-11-11T09:13:47.412Z,
updatedAt: 2021-11-12T02:32:08.212Z,
__v: 0
}
At comments.created_by
, the result still displays an object id instead of the user object. How can I resolve this?