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

slim :

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.

jstarnate :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=383447&siteId=1