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

131
Visualizações
Multiple updates on a single field causes "Updating the path 'X' would create a conflict at 'X'" in mongoDB

I have the following update operation:

private async onCategoryImagesModified(data: ModifiedFilesEventData) {
        this.categoryModel
            .findByIdAndUpdate(data.resourceId, {
                $pullAll: { images: data.removedFiles || [] },
                $addToSet: { images: { $each: data.addedFiles || [] } }
            }).catch(error => this.logger.warn(error))
}

Basically, every time images of model category changes I want to update the document by removing all the removed paths from images and adding the new paths to images.

I get that I can't reference the same field more than once inside an update, but is there a way to do this without 2 separate update operations?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I get that I can't reference the same field more than once inside an update

The update will not support the same field more than once, if you want to do this in the single query you can try update with aggregation pipeline starting from MongoDB 4.2,

  • $filter to iterate loop of images and remove the input elements by $not and $in
  • $setUnion to get unique elements from input elements and images field
private async onCategoryImagesModified(data: ModifiedFilesEventData) {
  let stages = [];
  // remove fields
  if (data.removedFiles) {
    stages.push({
      $set: {
        images: {
          $filter: {
            input: "$images",
            cond: { $not: { $in: ["$$this", data.removedFiles] } }
          }
        }
      }
    });
  }

  // add fields
  if (data.addedFiles) {
    stages.push({
      $set: { images: { $setUnion: ["$images", data.addedFiles] } }
    });
  }

  this.categoryModel
    .findByIdAndUpdate(data.resourceId, [stages])
    .catch(error => this.logger.warn(error))
}

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