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

127
Vistas
How can I update my raw mongodb database using get method?

I am trying to update my database using the get method, the reason behind updating the DB using the get method is because when the get method will be called a value will be increased automatically.

This is my code where I am trying to update the database inside the get method. It's possible by mongoose but I am using raw MongoDB to update it. is it possible to update? or any other way to update it automatically when /:shortUrl will be requested into the server.

  app.get('/:shortUrl', async (req, res) => {
            const filter = {
                short: req.params.shortUrl
            }


            const updateDoc = {
                $inc: {
                    clicks: 1
                }
            }

            const urlDoc = await bicycleAffiliateLinksCollection.findOneAndUpdate(filter, updateDoc, {
                new: false,
                upsert: true
            })

            console.log(urlDoc.value.short)
            res.redirect(`${urlDoc.value.full}?ref=${req.params.shortUrl}`)
            res.send({
                shortLink: urlDoc.value.short
            })
        })
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use $inc operator instead. Try refactoring the code as shown below:

app.get('/:shortUrl', async (req, res) => {
  const filter = {
    short: req.params.shortUrl
  }

  const updateDoc = {
    $inc: {
      clicks: 1
    }
  }

  const urlDoc = await bicycleAffiliateLinksCollection.findOneAndUpdate(filter, updateDoc, {
    new: true,
    upsert: true
  })

  console.log(urlDoc)

  res.send({
    shortLink: urlDoc.short
  })
})

upsert will create a new document if missing and new will return contents of the new document.

about 4 years ago · Juan Pablo Isaza 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