My MongoDB schema (simplified):
user: ObjectID
calories: Number
meals:[{
calories: Number
name:String
}]
And I have a updateMany query:
await Meals.updateMany(
{ user: user, 'meals.name': extraMealName },
{ $inc: { calories: 'meals.$.calories' } },
{multi : true},
function(error, result) {
console.log(error);
}
);
The query throws me this error:
CastError: Cast to Number failed for value "meals.$.calories" at path "calories"
I have tried changing the query for the last hour, but nothing worked… I also browsed stackoverflow, but found nothing I could work with
Does someone have an idea how to fix this?
2
Answers
the $inc has a syntax error, $inc expects a number not string so try some like this.
Using pipelined update,
mongoplayground
Updated for multiple fields.
Playground