Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Mongoose update array value

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?
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!