Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check reference collection has matched data or not in mongoose?

I have 2 simple collections as below.

  1. Product

    • Id
    • name
    • description
  2. likes

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    • 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"
  })

>Solution :

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", []] }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading