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

76
Views
Find object inside array and update document with Express and MongoDB

I have documents that contain objects inside an array. I need to be able to access the array and based on the _id of the object to be able to update it.

This is my model:


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

So I try to get by the ID of the document and the ID of the object inside the array so I can update it like this.

First attempt:

    const { idExp } = req.params; 
    const { idItem } = req.params; 

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

It only returns the complete document with all the objects inside the array.

second try:

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

It returns me the _id of the object, and items in an array that I can't access.

Thanks for your help.

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!