Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda