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

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

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 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!