I was trying to update the document with updateOne but got an error in code unable to access the previous value to update the field. getting type cast error. Using Mongoose version 7.0.1
invoiceSchema.updateOne({ appointmentId: convertIntoMongoId(invoiceDetail.appointmentId) },
{
$set: {
$inc: { pendingAmount: response.purchase_units[0].payments.captures[0].amount.value },
pendingAmount: { $subtract: ['$pendingAmount', response.purchase_units[0].payments.captures[0].amount.value] },
status: {
$cond: [
{
$and: [
{ $gt: ['$paidAmount', 0] },
{ $ne: ['$paidAmount', '$totalPayableAmount'] }
],
},
"Partially Paid",
"Not Paid",
]
}
}
}
)
}
{
"error": {
"error": {
"stringValue": "\"{ '$subtract': [ '$pendingAmount', '15.00' ] }\"",
"valueType": "Object",
"kind": "Number",
"value": {
"$subtract": [
"$pendingAmount",
"15.00"
]
},
"name": "CastError",
"message": "Cast to Number failed for value \"{ '$subtract': [ '$pendingAmount', '15.00' ] }\" (type Object) at path \"pendingAmount\""
}
},
}
You need to use Updates with Aggregation Pipeline. In short, wrap the
$setstage in square brackets[]to denote an aggregation pipeline. This will turn$pendingAmountinto the value of that field instead of the literal string$pendingAmountlike so: