In my model, I have an array of objects that I want to populate with new items when creating a NEW document. While I have found information on how to achieve this using findAndUpdate, I am struggling to figure out how to do it with the save() method.
This is the structure of my model:
const PettyCashItemsSchema = Schema (
{
pettyCashId:{
type: Schema.Types.ObjectId,
ref:'PettyCash',
required: [true, 'La Caja Chica es Obligatoria']
},
item: {
type: Number,
unique: true
},
items:[{
concept: {
type: String,
maxlength:50,
required: [true, 'El Concepto es obligatorio']
},
incomeAmount:{
type: Number,
maxlength:50,
default:0,
required: [true, 'El Ingreso es obligatorio']
},
expenseAmount:{
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']
}
}],
}
);
Below is the code snippet that I am using, but unfortunately, it does not add any new items to the array:
const pettyCashId= req.params.id;
const itemToPush = {
concept: req.body.concept,
incomeAmount: req.body.incomeAmount,
description: req.body.description,
'createdBy':{
uid: req.uid,
username: req.user.username,
}
};
const item = new PettyCashItems( { pettyCashId, $push: { 'items': itemToPush } } );
await item.save();
res.json ( item );
Thank you!