1

I have a list of posts and each post contains an array of comments, each comment might be private or public and I want to show Admins all private and public comments but normal users I want to show them only public comments.

here is a part of the post and comment Schema:

const PostSchema = new mongoose.Schema({
 title: String,
 comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
})

const CommentSchema = new mongoose.Schema({
 body: String,
 type: { type: String, enum: ['public', 'private'] }
})

here is the solution I came with: Grab the post by id:

const post= await Post.findById(id);

and then filter:

post.comments = post.comments.filter(c => c.type != "private");
return res.json(post)

but I want to do it full mongoose if that's possible.

2
  • Can a comment type have a value of both "public" and "private"? Because if no, you can just change the column type to public and set the data type to boolean (true or false). Commented Apr 1, 2020 at 15:01
  • you're right but how to get a post by id with only comments that have the value public: true? Commented Apr 1, 2020 at 15:07

1 Answer 1

2

Update your Comment schema:

const CommentSchema = new mongoose.Schema({
    body: String,
    public: Boolean,
    post: { type: Schema.Types.ObjectId, ref: 'Post' }
})

You can use mongoose's populate() method to extract the comments under a specific post. The match property is where you enter your query.

Post.findById(id)
    .populate({ path: 'comments', match: { 'type': 'public' } })
    .exec((err, postWithFilteredComments) => {
        res.json({ postWithFilteredComments })
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.