How to update array value in mongoose ?
This is my schema
var cars = new Schema({
brand : String,
prices:[ {color : String, price: String}]
}
let carID = req.body.carID;
let brandPriceArraySingleID = req.body.brandPriceArraySingleID;
var ObjectId = require('mongoose').Types.ObjectId;
var query = { 'prices.id' : new ObjectId(brandPriceArraySingleID) };
let carsPriceUpdate = await cars.findOneAndUpdate(query, { $set: { "price": "new price" } });
This above code is not working!!
Questions
If you want to update the Array fields element from the query, you need to use $ in the field, ex : { "prices.$.price": "new price" }
Try this code.
const query = {
_id : req.body.carID,
"prices._id" : req.body.brandPriceArraySingleID
}
let carsPriceUpdate = await cars.findOneAndUpdate(query, { $set: { "prices.$.price": "new price" },{ returnDocument: 'after' }});
console.log(carsPriceUpdate)
{ returnDocument: 'after' } is options of query. it's return document after updating.