Home > Enterprise >  UpdateMany isn't updating the data
UpdateMany isn't updating the data

Time:07-12

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?

CodePudding user response:

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

  • Related