2

I'm trying to create API to delete document on mongodb using mongoose.

Here's my route

router
    .route("/tasks")
    .delete('/:id', function (res, err) {
        taskSchema.findByIdAndRemove(req.params.id, (err, tasks) => {
            if (err) return res.status(500).send(err);
            const response = {
                message: "Todo successfully deleted",
                id: req.params.id
            };
            return res.status(200).send(response);
        });
    });

I get this error

Error: Route.delete() requires a callback function but got a [object String]

1 Answer 1

2

/tasks and /tasks/:id are two different routes and you should handle them as such, if you use /tasks to display all tasks, make a route for that, and make a second route for every interaction that you already have an ID for; aka deleting, updating, and use the route without the ID for interactions you don't have an ID for, like creating tasks:

router
  .route("/tasks")
    .get(/* return all tasks */)
    .post(/* create a task */);

router
  .route("/tasks/:id")
    .delete(function (req, res) {
        taskSchema.findByIdAndRemove(req.params.id, (err, tasks) => {
            if (err) return res.status(500).send(err);
            const response = {
                message: "Todo successfully deleted",
                id: req.params.id
            };
            return res.status(200).send(response);
        });
    });
Sign up to request clarification or add additional context in comments.

5 Comments

Totally Agree!!
I get the same error even after adding /:id to route
@HamzaHaddad Right, now it should work, I forgot to remove the extra first argument to the .delete()
I get req is not defined
you should not see that error anymore, you had more problems there than I saw in the first place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.