Home > Software engineering >  How to check reference collection has matched data or not in mongoose?
How to check reference collection has matched data or not in mongoose?

Time:12-20

I have 2 simple collections as below.

  1. Product

    • Id
    • name
    • description
  2. likes

    • id
    • userId
    • productId

Now I want a boolean key if the user liked that product or not.

Expected output:

  • _id
  • name
  • description
  • hasLiked

I have tried by lookup but it's not working.

.lookup({
    from: 'likes',
    let: {
      productId: "$productId"
    },
    pipeline: [
      {
        $match:
        {
          $expr:
          {
            $and:
              [
                { $eq: ["$productId", "$$_id"] }
              ]
          }
        }
      }
    ],
    as: "hasLiked"
  })

CodePudding user response:

First, you need to fix your lookup,

  • pass _id in productId key
  • check userId condition, input your userId
  • check the product id condition in the expression
.lookup({
    from: 'likes',
    let: { productId: "$_id" },
    pipeline: [
        {
            $match: {
                userId: "" // input your userId
                $expr: { $eq: ["$$productId", "$productId"] },
            }
        }
    ],
    as: "hasLiked"
})

Need to check condition in stage,

  • $ne to check hasLiked is not equal to [] then true otherwise false
.addFields({
    hasLiked: { $ne: ["$hasLiked", []] }
})
  • Related