首頁  >  問答  >  主體

MERN 應用程式無法從 MongoDB 中刪除項目

我有一些查詢要從 mongo 中刪除項目:

deleteCustomer: build.mutation({
        query: (id) => ({
            url: `client/cutomers/${id}`,
            method: 'DELETE',
            body: 'id',
        }),
        providesTags: ['DeleteUser'],
    }),

它在控制器中的外觀:

export const deleteCustomer = async (req, res) => {
    try {
        const { id } = req.params;
        const formattedUsers = User.findByIdAndDelete(id);
        res.status(200).json(formattedUsers);
    } catch (e) {
        res.status(404).json({ message: e.message })
    }
}

路線如何:

import express from "express";
import { getEmployees, getCustomers, getTransactions, getGeography, deleteCustomer, getCustomer } from "../controllers/client.js";

const router = express.Router();

router.get("/employees", getEmployees);
router.get("/customers", getCustomers);
router.get("/transactions", getTransactions);
router.get("/geography", getGeography);

router.get("/customers/:id", getCustomer);
router.delete("/customers/:id", deleteCustomer);

export default router;

一旦我要求從 byza 中刪除對象,我就會收到以下錯誤:

我已經驗證使用 fetch 時獲取請求可以正常工作。 這就是我提出請求的方式:

const [deleteCustomer] = useDeleteCustomerMutation()   

function handleDeleteUser(id) {
    // fetch('http://localhost:5001/client/customers/' + id, {
    //     method: 'GET',
        // })
        // .then(res => res.json())
        // .then(res => console.log(res))
        deleteCustomer(id)
    }

我相信我沒有在控制器層級正確實作deleteUser中的刪除功能。我非常感謝您關於解決此問題的建議:)

P粉427877676P粉427877676183 天前336

全部回覆(1)我來回復

  • P粉924915787

    P粉9249157872024-04-02 14:11:31

    查看您正在取得的路由 URL。在您的螢幕截圖上,您目前發出的發布請求網址似乎是 http://localhost:5001/client/cutomers/...

    我認為它在以下函數中:

    deleteCustomer: build.mutation({
            query: (id) => ({
                url: `client/cutomers/${id}`, // You put cutomers instead of customers
                method: 'DELETE',
                body: 'id',
            }),
            providesTags: ['DeleteUser'],
        }),
    

    這可以解釋為什麼你的伺服器給出 404 not found 回應。

    您可以嘗試進行更正並向我們提供更新嗎?

    回覆
    0
  • 取消回覆