Cannot remove data on MongoDB (MERN stack)

Hi there. I’m working on a MERN stack “to-do list” application which performs CRUD operations. It’s my first time working with MongoDB.

I could successfully implement “adding task to the database” functionality. However, for “removing task” I’m facing with Internal Server Error that I can’t fix although I’ve done research and tried multiple solutions.

I’m sharing related code snippets and I hope someone can help me a bit.

In my client folder, Task.jsx component:

function Task({ task }) {
    const { _id, taskId, title, description, completed } = task;
    const { userToken, dispatch } = useContext(TaskContext);

    const handleRemove = async (e) => {
        e.preventDefault();
        console.log("Task ID to remove:", _id);
    
        try {
            const res = await axios.get("/task/removeTask", {
                headers: {
                    Authorization: `Bearer ${userToken}`
                },
                params: {
                    _id: taskId
                }
            });
            console.log("Task deletion response:", res.data);
            dispatch({
                type: "REMOVE_TASK",
                _id
            });
        } catch (error) {
            console.error("Error removing task:", error);
            // Handle error state or display an error message to the user
        }
    }

taskReducer.js file:

function taskReducer(tasks, action) {
    console.log("taskreducer");
    switch (action.type) {
        // eslint-disable-next-line no-lone-blocks
        case "ADD_TASK": {
            return [
                ...tasks,
                {
                    _id: action._id,
                    title: action.title,
                    description: action.description,
                    completed: false
                }
            ]
        }
        case "SET_TASK": {
            return action.payload
        }
        case "REMOVE_TASK": {
            console.log("Tasks before removal:", tasks);
            const updatedTasks = tasks.filter((task) => task._id !== action._id);
            console.log("Tasks after removal:", updatedTasks);
            return updatedTasks;
        }

In my server folder, taskController.js file:

import taskModel from "../models/taskModel.js";
import userModel from "../models/userModel.js";
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();

const addTask = async (req, res) => {
    const { _id, title, description } = req.body;
    const userId = req.user.id;

    const user = await userModel.find({_id: userId});
    if (!user) {
        return res.status(404).json({ message: "User not found" });
    }

    const taskId = _id ? mongoose.Types.ObjectId(_id) : new mongoose.Types.ObjectId();

    console.log("Task to be saved:", { taskId, title, description, completed: false, userId });

    const newTask = new taskModel({ _id: taskId, title, description, completed: false, userId })

    newTask.save()
        .then((savedTask) => {
            return (res.status(200).json({ message: "Task added successfully", task: savedTask }))
        })
        .catch((error) => {
            return (
                res.status(500).json({ message: error.message })
            )
        }
        )
}

const removeTask = (req, res) => {
    const { _id } = req.body;
    const taskId = req.task._id;

    console.log("Task ID to remove:", _id); // Log the ID being used for deletion

    taskModel.findByIdAndDelete({ _id: taskId })
        .then((deletedTask) => {
            if (!deletedTask) {
                return res.status(404).json({ message: "Task not found" });
            }
            console.log("Deleted task:", deletedTask); // Log the deleted task
            return res.status(200).json({ message: "Task deleted successfully" });
        })
        .catch((error) => {
            console.error("Error deleting task:", error); // Log any errors
            return res.status(500).json({ message: "Internal server error" });
        });
}

const getTask = (req, res) => {
    taskModel.find({ userId: req.user.id })
        .lean() // Convert Mongoose documents to plain JavaScript objects
        .then((data) => res.status(200).json(data))
        .catch((error) => res.status(501).json({ message: error.message }))
}

export { addTask, getTask, removeTask }

taskRouter.js file:

router.post("/addTask", requireAuth, addTask)
router.get("/getTask", requireAuth, getTask)
router.get("/removeTask", requireAuth, removeTask)

Only removeTask function doesn’t work.

When I add a task, this is the response I’m getting on my browser console:

XHR OPTIONS http://localhost:8000/api/task/addTask[HTTP/1.1 204 No Content 6ms]
XHR POST http://localhost:8000/api/task/addTask[HTTP/1.1 200 OK 468ms]

When I click on the delete button to remove a task, this is the response:

Task ID to remove: 662e7dc365cc6fb9a0e14ed7 // matches the database
XHR OPTIONS http://localhost:8000/api/task/removeTask[HTTP/1.1 204 No Content 10ms]
XHR GET http://localhost:8000/api/task/removeTask[HTTP/1.1 500 Internal Server Error 1ms]
Error removing task: message: “Request failed with status code 500”, name: “AxiosError”, code: “ERR_BAD_RESPONSE”, config: {…}, request: XMLHttpRequest, response: {…} }

​I’ve also tried router.delete("/removeTask") and axios.delete("/task/removeTask") instead of GET method but nothing changed.

I hope you can enlight me a bit about the issue because I’m stucked up on this for a couple of days.

Thanks.

Hey @Rumeysa_Gelgi,

Welcome to the MongoDB Community forums :sparkles:

I haven’t done any repro to confirm the error you are encountering, but based on the error message, I suspect that in the taskController.js file, specifically within the removeTask function, you are attempting to access req.task._id , but req.task is not defined. Instead, you should use req.body._id since you are sending the task ID in the request body

Make sure you’ve made these changes and try again. If the issue persists, please let the us know and the community can further help you debug it.

Best regards,
Kushagra

Hi @Kushagra_Kesav,

Thank you. I’ve tried your answer but it didn’t work as well as there was no change on the error log. I’ve also tried req.params but still stucked up.

I’ve modified taskController.js removeTask function code:

const removeTask = (req, res) => {
    const { _id } = req.body;
    const taskId = _id ? mongoose.Types.ObjectId(_id) : new mongoose.Types.ObjectId();

    taskModel.findByIdAndDelete({ _id: taskId })
...

Now I can see the ID on the request URL but still receiving Internal Server Error

Task ID to remove: 662e7dc365cc6fb9a0e14ed7 [Task.jsx:14]
XHR OPTIONS http://localhost:8000/api/task/removeTask?_id=662e7dc365cc6fb9a0e14ed7[HTTP/1.1 204 No Content 2ms]
XHR GET http://localhost:8000/api/task/removeTask?_id=662e7dc365cc6fb9a0e14ed7[HTTP/1.1 500 Internal Server Error 2ms]