如何使用 get 方法更新原始 mongodb 数据库?

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

我正在尝试使用 get 方法更新我的数据库,使用 get 方法更新数据库的原因是因为当调用 get 方法时,值会自动增加。

这是我尝试在 get 方法中更新数据库的代码。猫鼬有可能,但我正在使用原始 MongoDB 来更新它。可以更新吗?或任何其他方式在 /:shortUrl 被请求进入服务器时自动更新它。

  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
            })
        })

您可以改用$inc operator。尝试重构代码,如下所示:

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 将创建一个新文档,new 将 return 新文档的内容。