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

320
Visualizações
Mongoose findOneAndUpdate() using current data

I am try to track the number of downloads per click on a website.

server.js

router.post("/download", async (req, res) => {
let id = req.body.id;
id = parseInt(id);

let doc = await db.findOneAndUpdate({_id: id}, {downloads: 100});
});

Note: This works

But I'm trying to increase the number by 1 each time.

For example: Let's say the current number of downloads is 5, how do I do it that if there's a post request. The number of downloads increases by 1.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

const { body: { id } } = req;
const intCasetedId = parseInt(id);
const retrievedDocument = await db.findOneAndUpdate({ id }, { $inc: { downloads: 1 } });

A couple things are happening here.

First I get the id value from the the req argument using a destructuring assignment.

I use only const to ensure I do not mutate variable values.

I also use the object property value shorthand notation to skip '_id' key in the search query argument. Quoting mongoose documentation:

Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

Then I am using '$inc' operator to increment the downloads field by 1.

I would also highly recommend for you to research eslint

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