简体   繁体   English

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

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

I'm building a todo app and in the database have an employee document containing 2 arrays (todo & done).我正在构建一个待办事项应用程序,并且在数据库中有一个包含 2 个数组(待办事项和已完成)的员工文档。 The tasks are stored here, and I currently can add tasks to the arrays, but I'm having trouble figuring out how to get my API work to delete them.任务存储在这里,我目前可以将任务添加到数组中,但我无法弄清楚如何让我的 API 工作以删除它们。

Here's what my employee doc looks like这是我的员工文档的样子

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

Currently I receive errors when trying to test using SoapUI, many similar to this "TypeError: Cannot read property 'findByIdAndDelete' of undefined" or Cannot DELETE /api/employees/1007/6184645df6bbd93340c0e390目前我在尝试使用 SoapUI 进行测试时收到错误,许多类似于“TypeError:无法读取未定义的属性 'findByIdAndDelete'”无法删除 /api/employees/1007/6184645df6bbd93340c0e390

Here's my delete API这是我的删除 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,
    });
  }
});

Currently, I can get messages to the console saying it's been deleted but it hasn't actually deleted in the database目前,我可以向控制台发送消息,说它已被删除,但实际上并未在数据库中删除

Welcome to stackoverflow!欢迎使用 stackoverflow! You should use updateOne with $pull.您应该将 updateOne 与 $pull 一起使用。 Try:尝试:

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

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

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

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

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