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

240
Views
Is there a way to update an object in an array of a document by query in Mongoose?

I have got a data structure:


{
  field: 1, 
  field: 3,
  field: [
    { _id: xxx , subfield: 1 },
    { _id: xxx , subfield: 1 },
  ] 
}

I need to update a certain element in the array.

So far I can only do that by pulling out old object and pushing in a new one, but it changes the file order.

My implementation:

            const product = await ProductModel.findOne({ _id: productID });
            const price = product.prices.find( (price: any) => price._id == id );

            if(!price) {
                throw {
                    type: 'ProductPriceError',
                    code: 404,
                    message: `Coundn't find price with provided ID: ${id}`,
                    success: false,
                }
            }

            product.prices.pull({ _id: id })
            product.prices.push(Object.assign(price, payload))
            await product.save()

and I wonder if there is any atomic way to implement that. Because this approach doesn't seem to be secured.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes, you can update a particular object in the array if you can find it. Have a look at the positional '$' operator here.

Your current implementation using mongoose will then be somewhat like this:

 await ProductModel.updateOne(
      { _id: productID, 'prices._id': id },//Finding Product with the particular price
      { $set: { 'prices.$.subField': subFieldValue } },
 );

Notice the '$' symbol in prices.$.subField. MongoDB is smart enough to only update the element at the index which was found by the query.

about 4 years ago · Juan Pablo Isaza 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!