繁体   English   中英

如何使用 findOneAndUpdate 检查是否没有要更新的文档

[英]How to check if there are no more documents to update using findOneAndUpdate

所以我正在为一个学校项目学习 CRUD,我遵循了一个非常有用的教程。 但是,当我完成它时,我注意到当没有更多要更新的报价时,它仍然会更新报价。 我该如何更改它以停止更新甚至不存在的报价?

  app.put('/quotes', (req, res) => {
    quoteCollection.findOneAndUpdate(
      { name: 'Yoda' },
      {
        $set: {
          name: req.body.name,
          quote: req.body.quote
        }
      },
      {upsert: true}
    )
    .then(result => {
      //The if block that i am trying
      if (result.deletedCount === 0) {
        return res.json('No quote to delete')
      }
    })
    .catch(error => console.error(error))
  })

你为什么要传递{name: "Yoda} ?这条路线应该只更新以 "Yoda" 作为其名称的报价?如果没有,那么你需要从请求 object 中获取应该更新的报价。

我尝试创建一个不同的版本,基于应该更新的报价将来自 req.body 的假设:

app.put("/quotes", async (req, res) => {
  //Grab the name/id/identifier for the quote you want to update from the body
  const query = req.body.name;

  // Try to update the document on the database
  try {
    const result = await quoteCollection.findOneAndUpdate(
      query,
      {
        name: req.body.name,
        quote: req.body.quote,
      },
      {
        upsert: true,
        new: true,
      }
    );

    // If it worked, it will return the updated quote
    res.status(200).json({
      status: 200,
      data: {
        result,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: "Something went wrong",
    });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM