I have a Mongoose Schema that looks like this:
{
_id: ObjectID,
storage: [{
location: String,
storedFood: [{
code: String,
name: String,
weight: Number
}]
}]
}
And for example in storedFood can be the same Food twice. But I only want to update one of the weights of these items.
This is my code to $inc all of the items…. How can I reduce this to only one?
try {
const deletedFoodFromStorage = await User.updateOne(
{_id: user, "storage.location": location},
{ $inc: {"storage.$.storedFood.$[food].weight": -weight}},
{ arrayFilters: [ { "food.code": code } ]},
);
res.json(deletedFoodFromStorage);
} catch(err) {
res.status(400).json('Error: ' + err)
}
3
Answers
Ty for your help!
The final solution for me was to restructure addStoredFood-Function to make the storedFood unique and only add weight to it instead of adding another objects.
This makes my old update-Function work aswell.
Should have been a simple one. Only way I found at the moment is not simple:
See how it works on the playground example
Borrowing liberally from nimrod serok’s answer, here’s one way to do it with a single pass through all the arrays. I suspect this can be improved, at least for clarity.
Try it on mongoplayground.net.