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
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.