slim
slim

Reputation: 55

Mongoose: how to filter an array of objects inside an object

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.

Upvotes: 1

Views: 1180

Answers (1)

jstarnate
jstarnate

Reputation: 329

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 })
    })

Upvotes: 2

Related Questions