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

84
Views
Encuentre el objeto dentro de la matriz y actualice el documento con Express y MongoDB

Tengo documentos que contienen objetos dentro de una matriz. Necesito poder acceder a la matriz y basándome en el _id del objeto para poder actualizarlo.

Este es mi modelo:

 import { Schema, model } from "mongoose"; const PettyCashSchema = Schema ( { createdAt: { type: Date, default: Date.now }, totalRevenue: { type: Number, maxlength:50, default:0, required: [true, 'El Total de Ingresos es obligatorio'] }, totalExpenditure: { type: Number, maxlength:50, default:0, required: [true, 'El Total de Egresos es obligatorio'] }, items:[{ item: { type: Number, unique: true, required: [true, 'El Item es obligatorio'] }, concept: { type: String, maxlength:50, required: [true, 'El Concepto es obligatorio'] }, revenue:{ type: Number, maxlength:50, default:0, required: [true, 'El Ingreso es obligatorio'] }, expenditure:{ type: Number, maxlength:50, default:0, required: [true, 'El Egreso es obligatorio'] }, description: { type: String, maxlength:50, required: [true, 'La Observación es obligatoria'] }, status: { type: Boolean, default: true, required: [true, 'El Estatus es obligatorio'] } }] } ); module.exports = model('PettyCash', PettyCashSchema);

Entonces trato de obtener la ID del documento y la ID del objeto dentro de la matriz para poder actualizarlo así.

Primer intento:

 const { idExp } = req.params; const { idItem } = req.params; let pettycash = await PettyCash.find( { "_id": idExp, "items._id": idItem } );

Solo devuelve el documento completo con todos los objetos dentro de la matriz.

segundo intento:

 let pettycash = await PettyCash.find( {"_id": idExp}, {items: {$elemMatch: {"_id": idItem}}});

Me devuelve el _id del objeto y los elementos de una matriz a los que no puedo acceder.

Gracias por tu ayuda.

about 4 years ago · Juan Pablo Isaza
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!