Hello, I have created an application which has a follower-followee feature. So if I follow user A and B, I will see posts from users A and B in my feed. People can comment on the post. Here is the query that I used:
const posts = await Post.aggregate([
// match followee posts
{
$lookup: {
from: 'followers',
localField: 'author',
foreignField: 'to',
as: 'rel'
}
},
{ $match: { 'rel.from': mongoose.Types.ObjectId(userId) }},
// Get first 2 comments
{
$lookup: {
from: 'comments',
as: 'comments',
let: { post_id: '$_id' },
pipeline: [
{
$match: {
$expr: { $eq: ['$post', '$$post_id'] }
}
},
{ $sort: { createdAt: -1 } },
{ $limit: 2 }
]
},
},
{
$project: {
'rel': 0
}
}
]).exec();
What it does is:
- Match the posts according to followee
- Attach the first 2 comments with each post
Now, I want to count total number of comments in each post and attach them with the post as totalComments
. What would the efficient approach to do this? I’ve wasted a lot of time behind this but can’t find a way