Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Número incremental en un objeto de matriz de mangosta

Estoy tratando de incrementar el número en MongoDB usando mangosta. Pero empiezo a fallar justo en la etapa de consulta. Cuando // @ts-ignore , fluye silenciosamente sin errores, pero el valor no se actualiza.

El error que arroja es: Type 'number' is not assignable to type 'undefined'

Mi esquema:

 const CartSchema: Schema<Document<ICart>> = new Schema({ clientID: { type: String, required: true }, sourceID: { type: String, required: true }, items: { id: { type: Types.ObjectId }, amount: { type: Number }, grindHow: { type: String, trim: true }, grind: Boolean, package: { type: String, trim: true }, price: { type: Number }, productID: { type: String }, productName: { type: String }, totalProduct: { type: Number }, }, source: { type: String, required: true }, }, { collection: "carts", timestamps: true }); CartSchema.virtual('cartTotal').get(function() { // @ts-ignore const self: any = this; if(self.items && self.items.length) { return self.items.reduce((acc: BigNumber, current: any) => acc.plus(current.totalProduct), new BigNumber(0)) } else { return 0 } })

La forma en que estoy tratando de implementar eso es:

 const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.$.amount': 1 }}).lean({ virtuals: true })

También probé con updateOne . Pensé que tal vez es más flexible.

Ahí es donde lo destaca.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

items no es una matriz, es un objeto. Debes acceder con items.amount y NO con items.$.amount . Cambia tu consulta así:

 const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.amount': 1 }}).lean({ virtuals: true })
over 4 years ago · Santiago Trujillo Report

0

El problema estaba en dos lugares allí.

El problema con mi esquema: lo describí como un objeto (gracias a @Nenad Milosavlievic) El esquema correcto es (o casi correcto. Cualquier sugerencia sobre el esquema es bienvenida):

 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 });

y otro problema con la forma en que estoy consultando el artículo. Debería haber convertido el ID de cadena en ObjectId . Me perdí eso...

Debería haber sido así (además, necesito devolver el valor actualizado, por lo que estoy agregando una opción { new: true } ):

 await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': Types.ObjectId(itemID) }, { $inc: { 'items.$.amount': 1 }}, { new: true }).lean({ virtuals: true })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!