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

128
Visualizações
How to keep decreasing value in mongo until is 0
singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })

The user clicks a button and the value of 'total_obj' gets decreased by one. The value doesn't have to be less than 0. I have tried to do this:

singleObj = await Objects.findByIdAndUpdate(
  { _id: req.body.id, "total_obj": { "$lt": 0 } },
  { "$set": { "total_obj": 0 } }
);

But this messes up every time I load the page and I have the values set to 0. I also added on the definition on the schema:

total_obj: {
    type: Number,
    required: true,
    min: 0
},
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I assume you meant that you don't want your value to be lesser than 0. You would need to use $gt operator and while you used $inc properly in the first findByIdAndUpdate you didn't use it in the second one.

Also, we are not looking only for id so we should use findOneAndUpdate instead.

singleObj = await Objects.findOneAndUpdate(
   { _id: req.body.id, "total_obj": { "$gt": 0 } },
   { $inc: { "total_obj": -1 } }
);
about 4 years ago · Juan Pablo Isaza Relatório

0

Try to fetch the Objects instance first and update the value only if > 0:

const singleObj = await Objects.findById(req.body.id)
if (!singleObj) // Error, obj not found
if (singleObj.total_obj > 0) {
    singleObj.total_obj = singleObj.total_obj-1
    await singleObj.save()
} else { 
    // `total_obj` is already zero 
}
about 4 years ago · Juan Pablo Isaza 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