How to Populate data using Aggregate function

I am trying to get data for an Application i am building.

The data will get Topics created by users along with the time it was posted, the most recent reply made by a user

i have these collections i need to work with: Forum, Reviews and User.

So far this is the code that i have written that works

const forum = await Forum.aggregate([
    {
      $lookup: {
        from: "users",
        localField: "createdBy",
        foreignField: "_id",
        as: "user",
        pipeline: [{ $project: { _id: 1, name: 1 } }],
      },
    },
    {
      $lookup: {
        from: "reviews",
        localField: "_id",
        foreignField: "forum",
        as: "review",
        pipeline: [
          { $unwind: "$user" },
          { $set: { "user._id": "$user" } },
          { $project: { _id: 1, user: 1, review: 1 } },
          { $sort: { createdAt: -1 } },
          { $limit: 1 },
        ],
      },
    },
  ]);

  res.status(200).json({
    status: "Success",
    result: forum.length,
    data: { forum },
  });

Please below is a screenshot of the output when i run on postman, the area i circled in red, i would like to know how i can get the detail of the user that made the review, i dont know what to do next in the code that wont slow down the performance of the Application

After doing some thinking, i was able to get the desired result, i discovered i didnt need to add the $unwind function, i only needed to add another $lookup function in the review pipeline to get what i was looking for, below is the code along with the screenshot from Postman.

  const forum = await Forum.aggregate([
    {
      $lookup: {
        from: "users",
        localField: "createdBy",
        foreignField: "_id",
        as: "user",
        pipeline: [{ $project: { _id: 1, name: 1 } }],
      },
    },
    {
      $lookup: {
        from: "reviews",
        localField: "_id",
        foreignField: "forum",
        as: "review",
        pipeline: [
          { $project: { _id: 0, user: 1, review: 1, createdAt: 1 } },
          { $sort: { createdAt: -1 } },
          { $limit: 1 },

          {
            $lookup: {
              from: "users",
              localField: "user",
              foreignField: "_id",
              as: "postBy",
              pipeline: [{ $project: { _id: 0, displayName: 1 } }],
            },
          },
        ],
      },
    },
  ]);

  res.status(200).json({
    status: "Success",
    result: forum.length,
    data: { forum },
  });

2 Likes