I am looking for a way to delete a product category along with all the products within it. The Product model has a reference to the category as an object.
Is there a straightforward method or a commonly used technique for this? I attempted to use removeAll but it returned an error saying that removeAll is not a function.
router.delete(`/category/:id/delete`, async (req, res) => {
try {
if (!req.params.id) res.send("missing id");
else {
await Product.removeAll({ category: req.params.id });
const categoryToDelete = await Category.findById(req.params.id);
await categoryToDelete.remove();
res.send("category deleted");
}
} catch (error) {
res.status(400).json({ error: error.message });
}
});
Thank you for sharing your expertise and assistance