猫鼬 findOneAndUpdate() 使用当前数据

Mongoose findOneAndUpdate() using current data

我正在尝试跟踪网站上每次点击的下载次数。

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

但我试图每次都将数字增加 1。

例如:假设当前下载次数为5,如果有post请求,我该怎么做。下载次数增加1.

const { body: { id } } = req;
const intCasetedId = parseInt(id);
const retrievedDocument = await db.findOneAndUpdate({ id }, { $inc: { downloads: 1 } });

这里发生了一些事情。

首先我从 req argument using a destructuring assignment.

中获取 id 值

我只使用 const 来确保我不会改变变量值。

我也用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 }, ...).

然后我使用“$inc”运算符将下载字段递增 1。

我也强烈建议您研究一下 eslint