Search code examples
javascriptmongodbmongoose

Mongoose/MongoDB: How can I $inc only the first value I get from an array?


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)
}

Solution

  • 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.