Home > OS >  Mongoose findOneAndUpdate() using current data
Mongoose findOneAndUpdate() using current data

Time:05-13

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.

CodePudding user response:

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

  • Related