Home > Blockchain >  Nodejs Mongoose how do I update an object in an array based the objects ID
Nodejs Mongoose how do I update an object in an array based the objects ID

Time:11-14

Here is my an example of a document from my "Cart" schema:

{ 
  _id: 1,
  line_items: [
    { item_id: 101, color: 'white', quantity: 1 },
    { item_id: 101, color: 'green', quantity: 1 },
    { item_id: 102, color: 'white', quantity: 1 },
  ]
}

I want to increase the quantity of the item which is uniquely identified by item_id = 101 and color = 'white'

I want it to be increase by x amount where x can be any number. How do I do this?

(edit 1) Here is what I have tried

await Cart.findById(1).then(doc => {
  const i = doc.line_items.findIndex(elm => { 
    return (elm.item == item && elm.color == color) // (edit 2) item is a variable = 101 and color is a variable = 'white'
  });
  doc.line_items[i].quantity  = quantity;
  doc.save();
}).catch(err => {
  throw err;
});

However, this isnt working because the changes in quantity aren't being saved to the database for some reason even though it is being updated when I console.log() it inside of this code.

I also beleive it should be possible to solve my problem with a single findByIdAndUpdate function though, but I have no idea how to do that

CodePudding user response:

I think you have a problem getting the index. I tried your code and it worked fine.

await Cart.findById
    .findById(1)
    .then((doc) => {
      const i = doc.line_items.findIndex((elm) => {
        //here is elm.item_id
        return elm.item_id == item && elm.color == color;
      });
      doc.line_items[i].quantity  = 10;
      doc.save();
    })
    .catch((err) => {
      throw err;
    });

CodePudding user response:

So apparently the reason my attempt did not work was because doc.save() was not being run because mongoose did not recognize any changes to the document. Why this is the case, I don't know, but by adding the line doc.markModified('line_items'); before saving, it is now working.

await Cart.findById(1).then(doc => {
  const i = doc.line_items.findIndex(elm => { 
    return (elm.item == 101 && elm.color == 'white')
  });
  doc.line_items[i].quantity  = 10;
  doc.markModified('line_items'); // <-- solution
  doc.save();
}).catch(err => {
  throw err;
});
  • Related