I have my model in Mongoose which inside has an array of objects. Inside this array I have an object called disabledBy to which I want to set data but Mongoose always tells me that it does not receive information for said object.
This is my Model:
Purchases
...
payments: [{
createdAt: {
type: String,
required:true
},
paymentNumber: {
type: Number,
default:0
},
previousBalance:{
type: Number,
required: [true, 'El Saldo anterior es obligatorio'],
default:0
},
paymentAmount:{
type: Number,
required: [true, 'La Cantidad del Pago(Abono) es obligatorio'],
default:0
},
outstandingBalance:{
type: Number,
required: [true, 'El Saldo pendiente es obligatorio'],
default:0
},
createdBy:{
uid : { type: String, required: true },
username:{ type: String, required: true }
},
comments: {
type: String,
maxlength:300,
},
status: {
type: Boolean,
default: true
},
disabledBy:{ // this is the object i try to update
uid:{
type: String,
required:true
},
username:{
type: String,
required:true
},
date:{
type: Date,
default: Date.now
},
comments: {
type: String,
maxlength:300,
required: [true, 'El Comentario es obligatorio']
}
}
}],
And this is my code from Express:
const payment = await Purchase.updateOne(
{ _id: id, 'payments._id': body.paymentId },
{
$set: {
'payments.$.status': false,
'payments.$.disabledBy': {
uid: req.user._id,
username: req.user.username,
comments: body.comments
}
}
} ,{ new: true });
It should be noted that when trying to update the status property of payments, it is executed correctly but not disabledBy.
This is the error reported by Mongoose:
error Purchase validation failed: payments.0.disabledBy.comments: El Comentario es obligatorio, payments.0.disabledBy.username: Path
disabledBy.username
is required., payments.0.disabledBy.uid: PathdisabledBy.uid
is required.
Even though the information I want to set in disabledBy is correct, I always get the Mongoose error. How can I set that information? Thanks.
CodePudding user response:
It's very strange but it only works if I remove the property from being required. Example of object without required working fine:
disabledBy:{
uid:{
type: String
},
username:{
type: String
},
date:{
type: Date,
default: Date.now
},
comments: {
type: String,
maxlength:300
}
}