1

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

  1. How to find and update array value?
  2. Do I need to check whether exist carID in cars model before array value find?
2
  • What is the value for brandPriceArraySingleID and what do you want to update? All prices? An specific price for a color in a brand? Commented Feb 17, 2022 at 15:37
  • thats object ID Commented Feb 21, 2022 at 6:03

1 Answer 1

1

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)
  1. You need to set new value for the object's property ( $ reflects the position).
  2. { returnDocument: 'after' } is options of query. it's return document after updating.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.