Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda