Deleting a product category along with all its products: Understanding the basics of CRUD操作

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

Answer №1

router.delete(`/category/:id/delete`, async (req, res) => {
try {
  if (!req.params.id) res.send("missing id");
  else {

    await Product.remove({ category: req.params.id });

    res.send("category deleted");
  }
 } catch (error) {
     res.status(400).json({ error: error.message });
  }
});

Simply input the query to be removed directly into the remove method, which will delete all matching documents of that category.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Three.js Collada for loading and displaying several Collada objects within Three.js framework

I am struggling to load multiple objects with collada and the solutions provided on stack overflow are not working for me. While I was successful in loading with three.js export, collada is giving me trouble. I have shared my code below. Any help would be ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

The map's content shifts with every scroll of the mouse, rather than being controlled by the

After creating a custom control in leaflet, I noticed that when interacting with it using scroll or click, the underlying map is affected instead of the control itself. <CustomMapControl> <div className="custom-c ...

Creating a custom Jquery function to generate a Div element instead of a Textbox in your web application

I need assistance with a jquery function that retrieves data from a JSON PHP MySQL setup. The retrieved results are currently displayed in textboxes. function showData(wine) { $('#Id').val(wine.id); $('#question').val(wine.question ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

Is it possible for Yarn to fail to include both ESM and CJS versions of a package during publishing or adding?

Our application is equipped with Parcel and utilizes a UI library consisting of react components. This UI library is built with Rollup and is privately published on NPM. I've been attempting to transition our application to Parcel 2, but I'm fac ...

React Error - The function 'deleteNinja' has not been declared and is undefined

I'm encountering an issue in Ninja.js where I am trying to delete state data by the Id passed as a prop. The error message I'm receiving is: Failed to compile src\Ninjas.js Line 11:41: 'deleteNinja' is not defined no-undef I&a ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

One effective way to redirect after a PUT request and display a one-time message

Here's what I'm aiming for in terms of desired behaviour: A user navigates to a password change web page. The user completes the form and it is sent via PUT request to our REST server. Upon successful completion, the user is redirected to their ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

JSON with an undefined or null value

Trying to access an API that contains a specific tree structure: {"19777621": [{ "queue": "RANKED_SOLO_5x5", "name": "Vladimir's Maulers", "entries": [{ "leaguePoints": 0, "isFreshBlood": false, "isHotStreak": true, " ...

The current issue with this javascript function is that it is failing to produce any output

function calculateOverallCGPA() { let cumulativeGPA = 0.00; for (let i = 1; i <= semNum; i++) { const GPAforOneSubject = parseFloat(getElementById(`subs${i}`).value); cumulativeGPA += GPAforOneSubject; } const finalCGPA = ...

Passing a method as a parameter type

As I delve into learning JavaScript from Objective-C, I find myself pondering whether it is possible to have a method with parameter types in Objective-C. Let's take the example of the findIndex() JavaScript function that identifies and returns the in ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...

Leveraging JS Variables within Twig Template

I am trying to incorporate a JavaScript variable into Twig. Despite attempting to implement the solution mentioned here, my code below does not render the map properly. If I remove the part between "var polylineCoordinates" and "polyline.setMap(map);", th ...

Could you provide a breakdown of the fundamental server configuration code for Express.js?

Consider the following code snippet: Const express = require('express') Const app = express(); /*Typeof express = function Typeof app = function*/ app.get() I am curious about how we are able to use a dot operator with a function like app ...

Executing a 'SELECT FROM' SQL query to MariaDB using Node.js

I have been attempting to execute a "select from" query on mariadb with the following code snippet. var mariadb = require('mariadb'); router.get('/redirect', auth.required, (req, res, next) => { const { payload: { id } } = req; ...