首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用findOneAndUpdate检查是否没有要更新的文档

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

Stack Overflow用户
提问于 2020-06-18 02:31:45
回答 1查看 14关注 0票数 0

因此,我正在为一个学校项目学习CRUD,并且我遵循了一个非常有用的教程。然而,当我完成它的时候,我注意到当没有更多的引用需要更新时,它仍然会更新引用。我如何更改这一点,使其停止更新甚至不在那里的报价?

代码语言:javascript
运行
复制
  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))
  })
EN

Stack Overflow用户

回答已采纳

发布于 2020-06-18 03:07:07

你为什么要通过{name: "Yoda}?此路由应该只更新名称为"Yoda“的报价吗?如果不是,那么您需要从请求对象中获取应该更新的报价。

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

代码语言:javascript
运行
复制
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",
    });
  }
});
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62435995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档