Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda