Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
Increment value of a property inside mongodb document using mongoose

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!