I am attempting to execute a PATCH update on a MongoDB document. I fetch the existing document using Mongoose in the following manner:
const ratePlan = await RatePlan.findOne({
_id: req.params.id,
})
The code snippets provided above work effectively in updating the model with the data from the HTTP request (req.body
):
for (const [key, value] of Object.entries(req.body)) {
ratePlan[key] = value
}
await ratePlan.save()
// - OR -
await RatePlan.replaceOne(
{ _id: ratePlan._id },
{
...ratePlan.toObject(),
...req.body,
},
{
overwriteDiscriminatorKey: true,
runValidators: true,
},
)
However, the following code snippet fails to update a specific field that consists of an array of objects (it only updates string and numeric fields):
await RatePlan.updateOne({ _id: ratePlan._id }, req.body, {
overwriteDiscriminatorKey: true,
runValidators: true,
})
What could be the reason for updating some fields while neglecting others?
Note: The RatePlan
model includes two discriminators, namely 'parent'
and 'child'
, with the discriminatorKey
set as 'kind'
. The field that is not being updated is exclusively found in the 'parent'
discriminator. The document undergoing the update also belongs to the 'parent'
discriminator.