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.