0

I am creating a forum and the structure is:

forum -> threads -> thread has a user

I wanted to aggregate it instead of populate, and my current code is:

const forums = await Forum.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(req.params.id),
      },
    },
    {
      $lookup: {
        from: "threads",
        localField: "_id",
        foreignField: "forumId",
        as: "threads",
      },
    },
    {
      $lookup: {
        from: "users",
        localField: "threads.user",
        foreignField: "_id",
        as: "threads.user",
      },
    },
  ]);

but the returned threads object has a user array, and it overrides all other thread values. I also want the user to be an object, instead of array of only one user. How Do i do that?

user14850280
  • 389
  • 3
  • 16

1 Answers1

0

I figured it out thanks to @turivishal

Code is:

 const forums = await Forum.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(req.params.id),
      },
    },
    {
      $lookup: {
        from: "threads",
        localField: "_id",
        foreignField: "forumId",
        as: "threads",
      },
    },
    {
      $unwind: "$threads",
    },
    {
      $lookup: {
        from: "users",
        localField: "threads.user",
        foreignField: "_id",
        as: "threads.user",
      },
    },
    {
      $unwind: "$threads.user",
    },
    {
      $group: {
        _id: "$_id",
        name: { $first: "$name" },
        threads: { $push: "$threads" },
      },
    },
  ]);

user14850280
  • 389
  • 3
  • 16