Update nested array in mongodb

Asked

Viewed 69 times

0

Hello,

I have been looking for a solution to my problem, which I will mention below, but I still haven’t found the right way to solve it, the solutions I find usually update the whole array rather than some specific elements.

Problem:

const user = await Users.getById(userID); // Um documento da coleção

for (let item of items) {
    const index = user.inventory.findIndex(element => element.id == item.id);

    if (index > -1) {
        user.inventory[index].quantity += item.quantity;
    } else {
        user.inventory.push(item);
    }
}

user.markModified('inventory');
await user.save();

I want to make only one request to the database and not two as my code is currently doing, one request to get the document and another to save.

1 answer

0

  • Thanks for the reply, but I’m already familiar with these methods, however I could not find any Operator query in the documentation of Mongo for my process.

  • $set does not suit?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.