简体   繁体   English

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

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

So I am learning CRUD for a school project and I followed a tutorial that was really useful.所以我正在为一个学校项目学习 CRUD,我遵循了一个非常有用的教程。 However, when I completed it I noticed that when there are no more quotes to update, it still updates quotes.但是,当我完成它时,我注意到当没有更多要更新的报价时,它仍然会更新报价。 How can I change this so that it will stop updating quotes that arent even there?我该如何更改它以停止更新甚至不存在的报价?

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

Why are you passing {name: "Yoda} ? This route is supposed to only update the quote with "Yoda" as its name? If not, then you need to grab from the request object the quote that should be updated.你为什么要传递{name: "Yoda} ?这条路线应该只更新以 "Yoda" 作为其名称的报价?如果没有,那么你需要从请求 object 中获取应该更新的报价。

I tried to create a different version, based on the assumption that the quote that should be updated will come from the req.body:我尝试创建一个不同的版本,基于应该更新的报价将来自 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