I have a below mongoose schema:
const PostSchema=mongoose.Schema({
author: String,
uid: String,
comments:[
{
commentAuthor: String,
uid: String,
comment: String,
userProfile: String,
dateOfComment: String,
replies: [{
replyAuthor: String,
authorProfile: String,
reply: String,
dateOfReply: String
}]
}
]
},{collection: 'SocialPost'});
I have fetch all those posts in which a particular user with a given id has commented i.e. all those documents in which comments array contains an object in which uid is equal to the given uid. For ex. suppose the user id is 101, then the result of the query might look like:
[{
author: 'gratis',
uid: 101,
...,
comments:[{
commentAuthor: 'gratis',
uid: 101,
...
},...]
},
...]
To put everything in perspective, I want to fetch all those posts on which a particular user has commented , or even replied, along with the comments and replies of only that user.
The best I could do is this:
SocialPost.aggregate([
{$match:{}},
{$unwind: "comments"},
{'$match': {"comments.uid": req.body.uid}}
])
This query is returning only the first matched item of comments array of respective post. I want all items that match the condition.
Please help me to design the right query for my problem.
Thank You!