George Akhobadze
George Akhobadze

Reputation: 1

mongoose .populate() is returning an empty array

I know this question has been asked a lot but I cant find a single solution that fixes my problem. populated comments in the post return an empty array, although the comment does exist with the corresponding post id.

I Have posts with reference to the comments like so:

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    status: { type: String, required: true },
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    createdAt: { type: Date, default: Date.now },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

and this is how i try to populate the comments:

const posts = await Post.find()
            .populate('author', 'username profileImage')
            .populate('comments');

this is how my comment schema looks:

const commentSchema = new mongoose.Schema({
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    content: { type: String, required: true },
    post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
    createdAt: { type: Date, default: Date.now }
});

Thank you for any help!

I tried linking the comments and posts, having comments with a post property that links to the post and vice versa.

Upvotes: 0

Views: 35

Answers (0)

Related Questions