首页 > 解决方案 > 删除请求有效,但不会从数据库中删除

问题描述

当我尝试通过 FindByIdAndDelete 删除项目时,它不会删除任何内容。当我在邮递员中发出删除请求时,我没有得到任何错误,只是数据库中的项目。我的 put 请求也发生了同样的情况。

那是我的代码:

router.delete("/", (req, res) => {
  Appointment.find({}, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

router.delete("/:id", (req, res) => {
  const id = req.params.id;

  Appointment.findByIdAndDelete(id, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

这就是我提出的要求:

{
"id": "5e3ef4950e1b4027201e73bf"
}

我究竟做错了什么?

标签: mongoosefindby

解决方案


findByIdAndDelete当它没有找到要删除的文档时不会抛出异常。您需要检查数据是否为空。

此外,您的第一条路线必须是 GET 路线而不是 DELETE。

router.get("/", (req, res) => {
  Appointment.find({}, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

router.delete("/:id", (req, res) => {
  const id = req.params.id;

  Appointment.findByIdAndDelete(id, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      if (data) {
        return res.json(data);
      } else {
        return res.status(400).send("Document not found, check id");
      }
    }
  });
});

推荐阅读