Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

319
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda