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

281
Visualizações
Conditional operator in mongoose

I am trying to conditionally execute two different mongoose operators but it just return no error and doesn't work to update the document.

My Schema:

const CartSchema: Schema<Document<ICart>> = new Schema({
    clientID: { type: String, required: true },
    sourceID: { type: String, required: true },
    items: { type: Array },
    source: { type: String, required: true },
}, { collection: "carts", timestamps: true });

The way I am trying to implement that:

await CartModel.findOneAndUpdate(
    { sourceID: clientID, 'items.id': Types.ObjectId(itemID) }, 
    { 
         $cond: { 
              if: {
                  $eq: 1,
              },
              then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
              else: { $inc: { 'items.$.amount': -1 }},
         }
    }, 
    { new: true }
).lean({ virtuals: true })

And I also tried to have this kind of query: { sourceID: clientID } but it didn't help. I thought maybe I could not find the element and it just silently pass through.

The main idea here of what I am gonna do is - have a conditional mongoose request where I'll either remove the object from the array if the current value in the field amount is equal to 1, or decrement the value to -1.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Apparently, the $cond operator works only in the aggregation framework but in my Atlas tier I cannot check if the query works properly, but I suppose it should look something like this:

           await CartModel.aggregate([
                { $match: {
                    sourceID: clientID, 
                    'items.id': Types.ObjectId(itemID)
                    }
                }, 
                { 
                    $cond: { 
                        if: {
                            $eq: 1,
                        },
                        then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
                        else: { $inc: { 'items.$.amount': -1 }},
                    }
                }
            ])
over 4 years ago · Santiago Trujillo 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