Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!