无法对MongoDB(MERN堆栈)执行CRUD(DELETE操作)

问题描述 投票:0回答:1

我正在开发一个执行 CRUD 操作的 MERN 堆栈“待办事项列表”应用程序。我可以成功实现“向数据库添加任务”功能。然而,对于“删除任务”,我面临着内部服务器错误,尽管我已经做了研究并尝试了多种解决方案,但我无法修复该错误。

我正在分享相关的代码片段,希望有人能帮助我。

在我的

client
文件夹中,
Task.jsx
组件:*EDITED

function Task({ task }) {
    const { _id, 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
                }
            });
            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
文件:

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;
        }

在我的

server
文件夹中,
taskController.js
文件:*已编辑

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;

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

    taskModel.findByIdAndDelete({ _id })
        .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 }

taskRoute.js
文件:

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

只有

removeTask
功能不起作用。

当我添加任务时,这是我在浏览器控制台上收到的响应:

XHR 选项 http://localhost:8000/api/task/addTask[HTTP/1.1 204 无内容 6ms]
XHR POST http://localhost:8000/api/task/addTask[HTTP/1.1 200 OK 468ms]

当我单击删除按钮删除任务时,响应如下:

要删除的任务 ID:662e7dc365cc6fb9a0e14ed7 // 与数据库匹配
XHR 选项 http://localhost:8000/api/task/removeTask[HTTP/1.1 204 无内容 10ms]
XHR GET http://localhost:8000/api/task/removeTask[HTTP/1.1 500 内部服务器错误 1ms]
删除任务时出错:消息:“请求失败,状态代码 500”,名称:“AxiosError”,代码:“ERR_BAD_RESPONSE”,配置:{...},请求:XMLHttpRequest,响应:{...} }

我也尝试过

router.delete("/removeTask")
axios.delete("/task/removeTask")
而不是
GET
方法,但没有任何改变。

我希望你能告诉我一些关于这个问题的信息,因为我已经在这个问题上坚持了几天了。谢谢。

编辑:

Error removing task: 
Object { stack: "AxiosError@http://localhost:3000/static/js/bundle.js:64350:18
settle@http://localhost:3000/static/js/bundle.js:65001:12
onloadend@http://localhost:3000/static/js/bundle.js:63696:66
EventHandlerNonNull*dispatchXhrRequest@http://localhost:3000/static/js/bundle.js:63709:7
./node_modules/axios/lib/adapters/xhr.js/__WEBPACK_DEFAULT_EXPORT__<@http://localhost:3000/static/js/bundle.js:63651:10
dispatchRequest@http://localhost:3000/static/js/bundle.js:64830:10
request@http://localhost:3000/static/js/bundle.js:64267:77
./node_modules/axios/lib/core/Axios.js/forEachMethodNoData/Axios.prototype[method]@http://localhost:3000/static/js/bundle.js:64289:17
wrap@http://localhost:3000/static/js/bundle.js:65402:15
handleRemove@http://localhost:3000/static/js/bundle.js:1828:81
callCallback@http://localhost:3000/static/js/bundle.js:29974:18
invokeGuardedCallbackDev@http://localhost:3000/static/js/bundle.js:30018:20
invokeGuardedCallback@http://localhost:3000/static/js/bundle.js:30075:35
invokeGuardedCallbackAndCatchFirstError@http://localhost:3000/static/js/bundle.js:30089:29
executeDispatch@http://localhost:3000/static/js/bundle.js:34233:46
processDispatchQueueItemsInOrder@http://localhost:3000/static/js/bundle.js:34259:26
processDispatchQueue@http://localhost:3000/static/js/bundle.js:34270:41
dispatchEventsForPlugins@http://localhost:3000/static/js/bundle.js:34279:27
./node_modules/react-dom/cjs/react-dom.development.js/dispatchEventForPluginEventSystem/<@http://localhost:3000/static/js/bundle.js:34439:16
batchedUpdates$1@http://localhost:3000/static/js/bundle.js:48831:16
batchedUpdates@http://localhost:3000/static/js/bundle.js:29822:16
dispatchEventForPluginEventSystem@http://localhost:3000/static/js/bundle.js:34438:21
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay@http://localhost:3000/static/js/bundle.js:31944:42
dispatchEvent@http://localhost:3000/static/js/bundle.js:31938:88
dispatchDiscreteEvent@http://localhost:3000/static/js/bundle.js:31915:22
EventListener.handleEvent*addEventBubbleListener@http://localhost:3000/static/js/bundle.js:32137:14
addTrappedEventListener@http://localhost:3000/static/js/bundle.js:34361:33
listenToNativeEvent@http://localhost:3000/static/js/bundle.js:34305:30
./node_modules/react-dom/cjs/react-dom.development.js/listenToAllSupportedEvents/<@http://localhost:3000/static/js/bundle.js:34316:34
listenToAllSupportedEvents@http://localhost:3000/static/js/bundle.js:34311:25
createRoot@http://localhost:3000/static/js/bundle.js:51594:33
createRoot$1@http://localhost:3000/static/js/bundle.js:51940:14
./node_modules/react-dom/client.js/exports.createRoot@http://localhost:3000/static/js/bundle.js:52016:16
./src/index.js@http://localhost:3000/static/js/bundle.js:2227:60
options.factory@http://localhost:3000/static/js/bundle.js:68791:31
__webpack_require__@http://localhost:3000/static/js/bundle.js:68237:33
@http://localhost:3000/static/js/bundle.js:69373:56
@http://localhost:3000/static/js/bundle.js:69375:12
", 
message: "Request failed with status code 500", 
name: "AxiosError", 
code: "ERR_BAD_RESPONSE", 
config: {…}, 
request: XMLHttpRequest, 
response: {…} 
}

编辑#2:

(我已经使用当前所做的修改编辑了上面的代码。这就是它现在的样子,同时收到以下错误。)

我已从

requireAuth
文件中的
router.get("/removeTask", requireAuth, removeTask)
中删除了
taskRoute.js
。我的服务器控制台日志回来了。

这是我的浏览器控制台上的完整错误日志:

Task ID to remove: 662e7dc365cc6fb9a0e14ed7 Task.jsx:14

XHR OPTIONS http://localhost:8000/api/task/removeTask?_id=662e7dc365cc6fb9a0e14ed7 [HTTP/1.1 204 No Content 9ms]

XHR GET http://localhost:8000/api/task/removeTask?_id=662e7dc365cc6fb9a0e14ed7 [HTTP/1.1 500 Internal Server Error 25ms]

Error removing task: 
Object { stack: "AxiosError@http://localhost:3000/static/js/bundle.js:64350:18\nsettle@http://localhost:3000/static/js/bundle.js:65001:12\nonloadend@http://localhost:3000/static/js/bundle.js:63696:66\nEventHandlerNonNull*dispatchXhrRequest@http://localhost:3000/static/js/bundle.js:63709:7\n./node_modules/axios/lib/adapters/xhr.js/__WEBPACK_DEFAULT_EXPORT__<@http://localhost:3000/static/js/bundle.js:63651:10\ndispatchRequest@http://localhost:3000/static/js/bundle.js:64830:10\nrequest@http://localhost:3000/static/js/bundle.js:64267:77\n./node_modules/axios/lib/core/Axios.js/forEachMethodNoData/Axios.prototype[method]@http://localhost:3000/static/js/bundle.js:64289:17\nwrap@http://localhost:3000/static/js/bundle.js:65402:15\nhandleRemove@http://localhost:3000/static/js/bundle.js:1828:81\ncallCallback@http://localhost:3000/static/js/bundle.js:29974:18\ninvokeGuardedCallbackDev@http://localhost:3000/static/js/bundle.js:30018:20\ninvokeGuardedCallback@http://localhost:3000/static/js/bundle.js:30075:35\ninvokeGuardedCallbackAndCatchFirstError@http://localhost:3000/static/js/bundle.js:30089:29\nexecuteDispatch@http://localhost:3000/static/js/bundle.js:34233:46\nprocessDispatchQueueItemsInOrder@http://localhost:3000/static/js/bundle.js:34259:26\nprocessDispatchQueue@http://localhost:3000/static/js/bundle.js:34270:41\ndispatchEventsForPlugins@http://localhost:3000/static/js/bundle.js:34279:27\n./node_modules/react-dom/cjs/react-dom.development.js/dispatchEventForPluginEventSystem/<@http://localhost:3000/static/js/bundle.js:34439:16\nbatchedUpdates$1@http://localhost:3000/static/js/bundle.js:48831:16\nbatchedUpdates@http://localhost:3000/static/js/bundle.js:29822:16\ndispatchEventForPluginEventSystem@http://localhost:3000/static/js/bundle.js:34438:21\ndispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay@http://localhost:3000/static/js/bundle.js:31944:42\ndispatchEvent@http://localhost:3000/static/js/bundle.js:31938:88\ndispatchDiscreteEvent@http://localhost:3000/static/js/bundle.js:31915:22\n", 
message: "Request failed with status code 500", 
name: "AxiosError", 
code: "ERR_BAD_RESPONSE", 
config: {…}, 
request: XMLHttpRequest, 
response: {…} }

这是我的服务器控制台上的完整错误日志:

Task ID to remove: undefined
Error deleting task: CastError: Cast to ObjectId failed for value "{ _id: undefined }" (type Object) at path "_id" for model "Task"
    at model.Query.exec (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\query.js:4913:21)
    at Query.then (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\query.js:5012:15)
    at removeTask (file:///C:/Users/Rumeysa/Downloads/mern-todo-app-master/server-side/controllers/taskController.js:40:10)
    at Layer.handle [as handle_request] (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\index.js:284:15  
    at Function.process_params (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\express\lib\router\index.js:280:10) {
  messageFormat: undefined,
  stringValue: '"{ _id: undefined }"',
  kind: 'ObjectId',
  value: { _id: undefined },
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
      at new BSONTypeError (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\bson\lib\objectid.js:67:23)
      at castObjectId (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\schema\objectid.js:246:12)
      at SchemaType.applySetters (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\schematype.js:1201:12)
      at SchemaType._castForQuery (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\schematype.js:1648:15)
      at SchemaType.castForQuery (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\schematype.js:1636:15)
      at SchemaType.castForQueryWrapper (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\schematype.js:1612:20)
      at cast (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\cast.js:293:34)      at Query.cast (C:\Users\Rumeysa\Downloads\mern-todo-app-master\server-side\node_modules\mongoose\lib\query.js:5341:12),
  valueType: 'Object'
}

这是 MongoDB 上的架构:

_id: ObjectId('662e7dc365cc6fb9a0e14ed7')
title: "Add TEST data"
description: "Add data"
userId: "6629874938bc9859f2505388"
completed: false
createdAt: 2024-04-28T16:48:03.875+00:00
updatedAt: 2024-04-28T16:48:03.875+00:00
__v: 0
javascript node.js mongodb mern internal-server-error
1个回答
0
投票

EDIT #2 之后,我还修改了以下语句,并且“删除任务”功能开始无缝工作。

taskController.js
文件中: 从
const { _id } = req.body
const { _id } = req.query;
taskModel.findByIdAndDelete({ _id })
taskModel.findByIdAndDelete( _id )

我还将

requireAuth
添加回
router.get("/removeTask", removeTask)
,一切都按预期工作,包括服务器控制台日志。为什么到目前为止
requireAuth
是一个问题,是因为我在
userToken
Bearer ${userToken}
const res = await axios.get("/task/removeTask", { headers: { Authorization: 
中定义了
 },
错误!我写了
Task.js
,而正确的说法是
const { userToken } = useContext(TaskContext);
我想感谢用户@we-do-the-best-for-you帮助我调试问题并引导我找到解决方案。

我正在编辑上面问题帖子中的所有代码,并进行正确的更改,以显示使应用程序正常工作的固定代码。

© www.soinside.com 2019 - 2024. All rights reserved.