Aggregation returning empty array

this is my code

``
`
app.get("/post/", async (req, res) => {
  try {
    const data = await databaseClient
      .db()
      .collection("user_card")
      .aggregate([
        {
          $lookup: {
            from: "members",
            localField: "userId",
            foreignField: "_id",
            as: "member"
          }
        },
        {
          $unwind: "$member"
        },
        {
          $project: {
            fullName: "$member.fullName",
            imagePath: "$member.imagePath",
            cardData: "$$ROOT"
          }
        }
      ])
      .toArray();

    res.status(200).json(data);
  } catch (err) {
    res.status(500).send(err);
  }
});

this sample data in members collection

_id:ObjectId('65c9c3fb6bdfb4d8a03b23e4')
fullName:"ttttttttt"
email:"ttttttt@gmail.com"
password:"$2b$10$7qQ1arg/Dxt4s1TrgPZ.x.BgfqW.M6d5MbXVYDNq5pn84np6yRcZy"
gender:"female"
dob:"2024-02-12"
phoneNumber:"099-999-9999"
typemem:"individual"
imagePath:"https://preview.redd.it/nq8ifla08ip51.jpg?width=640&crop=smart&auto=we…"



this sample data in user_card collection

_id:ObjectId('65ca263383d9b65d2e49497a')

userId:"65ca0a14790e5ea0ff510b84"

activityName:"asdasdasd"

activityType:"Cycling"

date:"2024-02-12"

durations:"60"

distance:"5000"

description:"asdasdasd"

imageUrl:"https://res.cloudinary.com/dzhbl6eju/image/upload/v1707747203/evaggi1u…"

createdAt:2024-02-12T14:07:47.679+00:00

Hello @Wp.Nan,

It looks like the data types of both collections is different,

The userId in user_card collection is the string type.

The _id in members collection is the objectId type.

I would suggest you always use objectId id type instead of just string type because it occupies less memory than string type and also match algorithm is faster than string type.

If it is a long process for you then you can convert the type in your aggregation query, there are multiple ways to achieve this, this is just an idea to convert userId to objectId using $toObjectId operator and match the condition.

  {
    $lookup: {
      from: "members",
      let: {
        userId: {
          $toObjectId: "$userId"
        }
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: ["$$userId", "$_id"]
            }
          }
        }
      ],
      as: "member"
    }
  }
2 Likes

thank you so much it means a lot :face_holding_back_tears: :pray:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.