getting error in nested population mongoose not working

13 Views Asked by At

I am not getting the user's name even after populating nested it shows an error if I try to access the user. the name of who did the comment

This is my comments Schema

const commentSchema = new mongoose.Schema({
content: {
    type: String,
    required: true 
},
user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
},
post: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Post'
}
},{
timestamps: true 
});

This is my Post Schema

 const postSchema = new mongoose.Schema({
 content: {
    type: String,
    required: true
 },
user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
},


comments: {
    type:'array',
    items: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Comment'
    }
}

}, {
timestamps: true
});

and my home controller is

 try {
    const posts = await Post.find()
    .populate('user')
    .populate('comments.user');

    for(post of posts){
        for(comment of post.comments){
            console.log(comment.user.name)
        }
        console.log('completed')
    }
    

    return res.render('home', {
        title: 'Codeal | Home',
        posts: posts
    })
} catch (error) {
    console.log('error in getting post ')
}

it shows the user id if I did only

 console.log(comment.user)

but when I do

  console.log(comment.user.name)

it show error in findig post

0

There are 0 best solutions below