I have 2 simple collections as below.
Product
- Id
- name
- description
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
inproductId
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 checkhasLiked
is not equal to[]
then true otherwise false
.addFields({
hasLiked: { $ne: ["$hasLiked", []] }
})