Mongoose: How to query nested document and return String result?
Generally it will return array of object when we project specific field from array of object,
Starting in MongoDB 4.4, as part of making find
projection consistent with aggregation’s $project
stage,
$reduce
to iterate loop ofvariation
array, check condition ifsku
match then it will returnprice
await Product.findOne({ "variation.sku": req.params.productVariationSKU },{ "_id": 0, variation: { $reduce: { input: "$variation", initialValue: 0, in: { $cond: [ { $eq: ["$$this.sku", req.params.productVariationSKU] }, "$$this.price", "$$value" ] } } }})
MongoDB 4.4 or below versions try aggregate()
,
let p = Product.aggregate();p.match({ "variation.sku": req.params.productVariationSKU });p.project({ _id: 0, variation: { $reduce: { input: "$variation", initialValue: 0, in: { $cond: [ { $eq: ["$$this.sku", req.params.productVariationSKU] }, "$$this.price", "$$value" ] } } }});res.send(await p.exec());