Mongoose: How to query nested document and return String result? Mongoose: How to query nested document and return String result? mongoose mongoose

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 of variation array, check condition if sku match then it will return price
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"        ]      }    }  }})

Playground


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());

Playground