繁体   English   中英

如何使用 mongoose 使用 API 删除数组中的某些内容?

[英]How can I use mongoose to delete something in an array using an API?

我正在构建一个待办事项应用程序,并且在数据库中有一个包含 2 个数组(待办事项和已完成)的员工文档。 任务存储在这里,我目前可以将任务添加到数组中,但我无法弄清楚如何让我的 API 工作以删除它们。

这是我的员工文档的样子

    {"_id":{"$oid":"61797a3ed15ad09b88d167ab"},"empId":"1008","password":"password2","firstName":"test","lastName":"user","__v":5,"done":[],"todo":[{"_id":{"$oid":"61870bfe6ac33427b8406f7d"},"text":"testtask","id":"1"}]}

目前我在尝试使用 SoapUI 进行测试时收到错误,许多类似于“TypeError:无法读取未定义的属性 'findByIdAndDelete'”无法删除 /api/employees/1007/6184645df6bbd93340c0e390

这是我的删除 API

*
 * Delete task
 */
router.delete("/:empId/tasks/:id", async (req, res) => {
  try {
    Employee.findByIdAndDelete(
      { _id: req.params.id },
      function (err, employee) {
        if (err) {
          console.log(err);
          res.status(500).send({
            message: "Internal server error: " + err.message,
          });
        } else {
          console.log(employee);

          console.log(
            "Task with the id of" +
              req.params.id +
              " has been deleted successfully"
          );
          res.json(employee);
        }
      }
    );
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: "Internal server error: " + e.message,
    });
  }
});

目前,我可以向控制台发送消息,说它已被删除,但实际上并未在数据库中删除

欢迎使用 stackoverflow! 您应该将 updateOne 与 $pull 一起使用。 尝试:

Employee.updateOne({
  empId: req.params.empId
}, {
  $pull: {
    todo: {
      _id: req.params.id
    }
  }
})

参考: https : //stackoverflow.com/a/27917378/9459826

MongoDB 文档:https ://docs.mongodb.com/manual/reference/operator/update/pull/

暂无
暂无

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

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