I have an app that looks like this picture 1
I choose checkboxes and after I press mass delete and in state I have array of ids which I have chosen (picture 2) My delete function in controllers looks the following
const deleteProduct = async (req, res) => {
const { id: productId } = req.params;
const product = await Product.findOne({ _id: productId });
console.log(product);
if (!product) {
throw new Error(`No product with ${productId}`);
}
await product.remove();
res.status(200).json({ msg: "Success, product removed" });
};
But this function works in postman only on route
router.route("/:id").delete(deleteProduct)
How to write a function which takes the array of items and a route for that?
CodePudding user response:
First of all, its unclear what method do you use (POST or GET) ?
GET method:
URL example
my-api/products?array[]=1&array[]=2&array[]=3
Then you can read array
variable as follows:
route.get('my-api/products', (req, res) => {
console.log(req.query.array); // [1, 2, 3]
})
POST method:
You have to send POST request to your endpoint (e.g. with axios
):
axios.post('my-api/products', {
selectedItems: [] // your array of ids
})
then read ids
array
route.post('my-api/products', (req, res) => {
console.log(req.body.selectedItems); // [1, 2, 3]
})