Facing difficulty with aggregation

Hi everyone. I’m new here and also new to MongoDB

I have an array of user ids userIds = ["1", "2"]

I want to be able to get the user’s object from the user’s collection using the above array, and save the user objects in a new array called ‘users’. That is users = [{user1Obj}, {user2Obj}]

[
    {
      "_id": "8b7baf2cebaa41c9aff9ed9f97f661e9",
      "messages": [],
      "userIds": [
        "64656d299920c3e937f4d6cc",
        "64656be5ba1496a420fdce38"
      ],
      "chatInitiator": "64656be5ba1496a420fdce38",
      "createdAt": "2023-05-19T03:00:25.447Z",
      "updatedAt": "2023-05-19T03:00:25.447Z",
      "__v": 0,
    }
 ]

I want it transformed to

[
    {
      "_id": "8b7baf2cebaa41c9aff9ed9f97f661e9",
      "messages": [],
      "chatInitiator": "64656be5ba1496a420fdce38",
      "createdAt": "2023-05-19T03:00:25.447Z",
      "updatedAt": "2023-05-19T03:00:25.447Z",
      "__v": 0,
      "users": [
         user1Obj,
         user2Obj
       ]
   }
]

Below is what I have done but it’s not giving me the expected result

Model.aggregate([
      { $match: { userIds: { $in: [userId] } } },
      { $sort: { createdAt: -1 } },
      {
        $lookup: {
          from: "users",
          localField: "userIds[]",
          foreignField: "_id",
          as: "users"
        }
      },
      {
        $addFields: {
          users: {
            $map: {
              input: "$users",
              as: "user",
              in: "$$user"
            }
          }
        }
      },
      {
        $unset: "userIds"
      },
      // pagination
      { $skip: options.page * options.limit },
      { $limit: options.limit },
      { $sort: { createdAt: 1 } },
    ]);`

Any help?

1 - Try with `localField: “userIds” rather than:

2 - your $addFields is probably useless since you $map each $$user to itself

3 - your 2nd $sort is useless