0

I'm building a todo app and in the database have an employee document containing 2 arrays (todo & done). 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.

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

Here's my delete 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

john f
  • 1

1 Answers1

0

Welcome to stackoverflow! You should use updateOne with $pull. Try:

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

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

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

Orlando
  • 232
  • 2
  • 8
  • thanks , would i still use router.delete? or something like router.put – john f Nov 07 '21 at 01:02
  • I've implemented this solution but keep receiving 404 errors in the console, wonder if it has something to do with my routes – john f Nov 07 '21 at 01:21
  • Well, yeah. If you're receiving a 404, then it probably has something to do with routing. About the method you're using, given you're deleting an item from a subdocument, it's okay to use delete. Bear in mind, using delete or put shouldn't be the reason why you're getting a 404. Have you tried to test it using HTTP clients such as insomnia? – Orlando Nov 07 '21 at 14:04
  • Also, in the example you gave "6184645df6bbd93340c0e390", this id isn't in the employee doc you've shown us as well. Try with empId 1008 and task 61870bfe6ac33427b8406f7d – Orlando Nov 07 '21 at 14:07