Reputation: 929
Here is my code.
Cart
.aggregate()
.match(where)
.lookup({
from: "product_catelogs",
foreignField: "_id",
localField: "product_id",
as: "product"
})
.project({
product: {
$arrayElemAt: ["$product", 0]
},
"product.custom_field": {
$add: [1, 1]
},
product_quantity: 1,
product_variant: 1,
guest_token: 1,
user_id: 1,
product_id: 1,
})
In this I want to add a custom field with product object. but when I am trying to do so, I am facing this kind of error,
can't add an expression for a subfield of product because there is already an expression that applies to the whole field
Please help me out.
Upvotes: 0
Views: 473
Reputation: 103365
I'm afraid the only way you could go about this is to add another project pipeline that has projections of the product
embedded fields individually together with the new field. An example follows:
Cart.aggregate()
.match(where)
.lookup({
"from": "product_catelogs",
"foreignField": "_id",
"localField": "product_id",
"as": "product"
})
.project({
"product": { "$arrayElemAt": ["$product", 0] },
"product_quantity": 1,
"product_variant": 1,
"guest_token": 1,
"user_id": 1,
"product_id": 1,
})
.project({
"product.field1": "$product.field1", // <-- change to suit your actual schema
"product.field2": "$product.field2",
"product.field3": "$product.field3",
"product.field4": "$product.field4",
"product.custom_field": { "$add": ["$product.field4", "$product.field5"] },
"product_quantity": 1,
"product_variant": 1,
"guest_token": 1,
"user_id": 1,
"product_id": 1,
})
Upvotes: 2