how too use $lookup in mongoose to fetch array object

Viewed 29

I have the following aggregation and It does not return the user profiles properly

   const newConverSation = await Messenger.Messenger.aggregate([
    { $match: {
        users: mongoose.Types.ObjectId("6084036ad4d4cd40a47afba4")}},
    { $sort: { updatedAt: -1 } },
    {
      $group: {
        _id: { $setUnion: "$users" },
        message: { $first: "$$ROOT" }
      }
    },
   {
    $lookup: {
        from: 'users',
        localField: 'users',
        foreignField: '_id',
        as: 'users'
    }
   }
  ])

In the outcome, there is an users array like this

 "users" : [ 
        ObjectId("60841d03f6ccad2b0400f619"), 
        ObjectId("6084036ad4d4cd40a47afba4")
    ],

and I just want to fetch user profiles depending on these two Id's but it does not return profiles in the current way.

1 Answers

Try adding the .populate after the .find property where you want to show this data.

Related