Home  >  Q&A  >  body text

MERN application cannot delete items from MongoDB

I have some queries to delete items from mongo:

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

How it looks in the controller:

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

How about the route:

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;

As soon as I request to delete the object from byza, I get the following error:

I've verified that get requests work fine when using fetch. This is how I made the request:

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

I believe I'm not implementing the delete functionality in deleteUser correctly at the controller level. I would really appreciate your suggestions on how to fix this problem :)

P粉427877676P粉427877676225 days ago397

reply all(1)I'll reply

  • P粉924915787

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

    View the route URL you are getting. On your screenshot, it appears that the post request URL you are currently making is http://localhost:5001/client/cutomers/...

    I think it's in the following function:

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

    This may explain why your server is giving a 404 not found response.

    Can you try to make a correction and provide us with an update?

    reply
    0
  • Cancelreply