'How do I query to fetch number of Posts made by a User using mongoose?
So I'm trying to fetch the total number of posts done by a specific user.
Models
Post.ts (In post model I have user ref)
user: {
type: Schema.Types.ObjectId,
ref: "User",
required: [true, "Please provide user ID."],
},
I tried
const posts = await Post.find({ user: req.user._id});
const postCount = posts.length;
But I want to aggregate the User so I can get the user data along with the post counts. what I tried is below but I'm getting 0 number of posts.
const user = await User.aggregate([
{
$lookup: {
from: "post",
let: { userId: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$$userId", "$userId"] } } }],
as: "posts_count",
},
},
{ $addFields: { posts_count: { $size: "$posts_count" } } },
]);
I searched but couldn't find any related answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
