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

85
Views
UpdateMany isn't updating the data

In user schema, Location is an array of objects with locations._id is ObjectId.

This is my user service file.

const updatedBy = {
  _id: mongoose.Types.ObjectId(req.params.id),
  "locations._id": { $in: req.body.locationIds },
};
const updatingData = { $set: { "locations.$.status": req.query.status }};
const user = await userDbServices.updateRecords(updatedBy, updatingData);

In req.body.locationIds, I'm passing an array.

And this one is the user DB service file

exports.updateRecords = async function (updateParam, updatingData) {
  return userModel.updateMany(updateParam, updatingData);
};

When I hit the API, The first embedded document of location is updated. But the other ones aren't. How can I solve this?

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

0

This is actually the expected behavior of the $ identifier, from the docs:

the positional $ operator acts as a placeholder for the first element that matches the query document

To update multiple elements you want to be using the $[] identifier with arrayFilters, like so:

userModel.updateMany({
  _id: mongoose.Types.ObjectId(req.params.id),
  "locations._id": { $in: req.body.locationIds },
},
{
  $set: {
    "locations.$[elem].status": req.query.status
  }
},
{
  arrayFilters: [
    {
      "elem._id": {
        $in: req.body.locationIds
      }
    }
  ]
})

Mongo Playground

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!