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 },
});
