Increment value of a property inside mongodb document using mongoose

Viewed 294

So I have this array of objects called "items":

Array

and for each object, I want to find the same object in mongodb using the "baseId" in the Base Document, and then update the "jumlahTerjual" amount by +1, this is the "Base Document": enter image description here

I've tried this method but got an error called "jumlahTerjual is not defined": enter image description here

How can I update it using findByIdAndUpdate correctly? Any answer will be so much appreciated.

1 Answers

Assuming the jumlahTerjual key exists for each object in you base document, when you want to increment it (by any custom value), try:

items.map(item => {
  return Base.findByIdAndUpdate(item.baseId, {$inc: { jumlahTerjual: 1 }}, function(error, counter) {
    if(error)
      return next(error);
    doc.testvalue = counter.seq;
    next();
  })
})

Use the $inc operator instead of { jumlahTerjual: jumlahTerjual + 1 } as the update object. Because, currently the interpreter tries to find a local variable called jumlahTerjual which is being incremented by 1 and being assigned to the key in the object found by mongoose. Because we haven't defined a local variable for jumlahTerjual that is why you get the undefined error.

Because you only want to increment, instead of changing the value in the mongoDB record with a new value just use the $inc operator.

Related