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.
CodePudding user response:
You can slightly alter the query as follows. From the post
model, I see that the field referenced for user collection is user
. In the aggregate, you have used $userId
.
const user = await User.aggregate([
{
$lookup: {
from: "post",
let: { userId: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$$userId", "$user"] } } }],
as: "posts_count",
},
},
{ $addFields: { posts_count: { $size: "$posts_count" } } },
]);
Let me know if this helps. Thanks