Home > Software engineering >  Delete multiple array // "route doesn't exist"
Delete multiple array // "route doesn't exist"

Time:04-11

I tried to delete the array of multiple elements but I guess I do something wrong.

My app looks like this picture

So, when I press on mass delete I get an error that the route doesn't exist (picture) I think it's because in my node route look like

import express from "express";
const router = express.Router();
import {
  createProduct,
  getAllProducts,
  deleteProduct,
} from "../controllers/productController.js";

router.route("/createProduct").post(createProduct);
router.route("/").get(getAllProducts);
router.route("/:id").delete(deleteProduct);

export default router;

I tried in postman and it's successful, I think because I pass by id, but now in my state I have selected items array and its a bunch of ids picture So, how in route write that it's an array? Thanks in advance

CodePudding user response:

The error is because the only delete endpoint that exists is the one where you pass an id as the parameter router.route("/:id").delete(deleteProduct);, so when you target localhost:5000/api/v1/ with a HTTP DELETE it throws a 404 error.

For multiple deletion you can maybe create a new route say:

router.route("/deleteMassProducts").delete(deleteMassProducts);

you can then send the array of selected items in the request body and then delete them with whatever logic you prefer. You can also accomplish this without changing anything on the backend, just loop through the selected items and target the delete route with the :id parameter multiple times for each of the selected items id.

  • Related