Please help in fetching the data of user with posts info

Hey there, I want to fetch the user details by passing _id and I also want the total no. of posts made by him/her should also be fetched. So please help me in getting it done.

This is an example :point_down: of how I am doing it.

    const userDataList = await models.User.aggregate([
      {
        $match: {
          _id: new mongoose.Types.ObjectId(_id),
        },
      },

      {
        $set: {
          userData: { $first: "$userData" },
        },
      },

      {
        $unset: ["user"],
      },

      {
        $lookup: {
          from: "cards",
          localField: "_id",
          foreignField: "creator.id",
          as: "cards",
        },
      },

      {
        $lookup: {
          from: "cards",
          let: { userId: "$_id" },
          pipeline: [
            {
              $facet: {
                count: [
                  {
                    $match: {
// need help here
},
                  },
                ],
              },
            },
            {
              $count: "totafdafd",
            },
          ],
          as: "totalCards",
        },
      },

    ]);

Hi :wave: @Taranpreet_Singh1,

Welcome to the MongoDB Community forums :sparkles:

Could you please share the sample data set of each of the collections (being used here) for a better understanding of the schema of your application?

Regards,
Kushagra

1 Like