Trouble arises when attempting to remove an object using a combination of Node.JS, Mongoose, MongoDB, and

In my setup, I have two collections: one is called subcategories and the other is called categories. The categories collection includes a field known as subcategories which is an array containing the ids of the subcategories from the subcategories collection.

To accomplish the task of deleting a specific subcategory within a category, I have created an endpoint labeled DELETE /categories/categoryId/subcategories/subcategoryId

subcategories.delete('/:categoryId/subcategories/:subcategoryId', async (req, res) => {
  try {
    const category = await Category.findById(req.params.categoryId);
    if(!category) return res.status(404).send("Category is not found");
    category.subCategories.remove( req.params.subcategoryId );
    const subCategory = await SubCategory.findByIdAndRemove(req.params.subcategoryId);
    if(!subCategory) return res.status(404).send("Subcategory is not found");
    res.status(202).send("Subcategory is deleted successfully");
  } catch (error) {
    res.send(error.message);
  }
}

My goal is to efficiently remove the id of the deleted subcategory from the subcategories array present in the category model.

category.subCategories.remove( req.params.subcategoryId );

Despite attempting the aforementioned line of code, I encountered issues with its functionality while utilizing Mongoose, MongoDB, and Express.

Answer №1

Here is the locally reproduced code:

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/test2345", {
    useNewUrlParser: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", async function() {


    await mongoose.connection.db.dropDatabase();
    // we're connected!

    console.log("Connected");

    const subcategoriesSchema = new mongoose.Schema({
        name: String
    });

    const categoriesSchema = new mongoose.Schema({
        name: String,
        subcategories: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Subcategory' //Edit: I'd put the schema. Silly me.
        }]
    });

    const Subcategory = mongoose.model("Subcategory", subcategoriesSchema);
    const Category = mongoose.model("Category", categoriesSchema);

    const cat1 = new Subcategory({
        name: "Pop"
    });
    const cat2 = new Subcategory({
        name: "Rock"
    });

    await cat1.save();
    await cat2.save();

    const ubercat = new Category({
        name: "Music",
        subcategories: [cat1._id, cat2._id]
    });
    await ubercat.save();

    async function removeSubcategory(categoryId, subcategoryId) {
        try {
            const category = await Category.findById(categoryId);
            if (!category) {
                console.log("No such category");
                return null
            }
            category.subcategories.remove(subcategoryId);
            category.save();
            console.log(subcategoryId);
            const subCategory = await Subcategory.findByIdAndRemove(subcategoryId);
            if (!subCategory) {
                console.log("No such subcategory");
                return null
            }
            console.log("Subcategory is deleted successfully");
        } catch (error) {
            console.log(error.message);
        }
    }

    await Subcategory.find(function(err, subcats) {
        if (err) return console.error(err);
        console.log(subcats);
    });

    await Category.find(function(err, cats) {
        if (err) return console.error(err);
        console.log(cats);
    });

    await removeSubcategory(ubercat._id, ubercat.subcategories[0]._id);
    console.log("After modification.");
    await Category.find(function(err, cats) {
        if (err) return console.error(err);
        console.log(cats);
    });

});

The issue with your script is that after

category.subCategories.remove( req.params.subcategoryId );
, you are missing category.save();, causing the transaction not to commit to the DB.

Output after adding save:

Connected
[ { _id: 5f439bf63224885dbc87e5cf, name: 'Pop', __v: 0 },
  { _id: 5f439bf63224885dbc87e5d0, name: 'Rock', __v: 0 } ]
[ { subcategories: [ 5f439bf63224885dbc87e5cf, 5f439bf63224885dbc87e5d0 ],
    _id: 5f439bf63224885dbc87e5d1,
    name: 'Music',
    __v: 0 } ]
5f439bf63224885dbc87e5cf
(node:23996) DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify
Subcategory is deleted successfully
After modification.
[ { subcategories: [ 5f439bf63224885dbc87e5d0 ],
    _id: 5f439bf63224885dbc87e5d1,
    name: 'Music',
    __v: 1 } ]

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

Transfer information from the server to the client using NodeJS and Express

I am encountering an issue with sending data from my express server to the client side. I have implemented app.post and app.get, however the problem is that the request needs to originate from the client side. My requirement is to send the data from the se ...

Executing Nightwatch.js Upload Command

Looking to develop a nightwatch action that involves uploading files to a specific upload form. Can an action like this be created within the nightwatch framework? Nightwatch is linked to a nodejs app and operates through a selenium webdriver. ...

Unable to upload multiple files using formidable in Node.js

app.post('/upload', function (req, res) { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { try{ if (files.file.name != '') { file_newname = dt.MD5(files.file.name ...

Can you explain the distinction between server-side rendering in Next.js and static site rendering in Gatsby.js?

I'm interested in developing a website without depending on client-side JavaScript, but I still want to incorporate SPA features such as client-side routing. To achieve this, I am considering using a framework that does not rely on rendering on the cl ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

Guide on deploying a personalized SDK alongside your nodejs application on the Azure platform

I have created an SDK.js to simplify the usage of my API on Azure, which is supported by my nodejs server. What is the most efficient method for deploying this SDK.js to the server so that clients can easily incorporate it into their code using a script t ...

Navigating to URL with Query String correctly using Express

Below is the code I currently have: app.get('/', function (req, res) { req.query.searchQuery = 'test2' res.redirect('/search'); }); app.get('/search/', function (req, res) { var searchQuery = req.query.search ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

How to Resolve ENOENT ERROR When Using fs.unlink in an Express.js Simple Application?

Currently, I am developing a basic blog using express.js. For managing the posts, I have opted for Typicode/lowdb as my database. The posts are created, updated, and deleted based on unique IDs stored in a data.json file. Additionally, I utilize the slug d ...

What methods can I use to conceal a Script within a particular subDomain in Next.js?

on the main website page, there is a chat window script that needs to be hidden on any subdomain, for example: domain.com >> allow the Script ,,,, *.domain.com >> disallow the Script *.domain.com/* >> disallow the Script import { Html ...

Issue with Facebook passport/local passport conflict preventing login using Facebook account

Recently, I encountered an issue while trying to implement a login feature using Facebook and passport.js. Although my local login with passport worked smoothly, integrating it with Facebook posed some challenges. My tech stack includes express, mongoose, ...

Retrieve an array of data from Sequelize without any wrapping objects

Hello, I am facing an issue with the query from Sequelize that I have below. models.ProviderZoneCity.findAll({ attributes: ['zoneId'], raw : true, where : { status : 1 ...

Using callbacks in Node.js to pass variables

I'm relatively new to working with node and I'm attempting to develop a function that retrieves server information. However, I've encountered an issue. I've set up a config object (which will eventually be dynamically updated by certain ...

Troubleshooting: Angular2 and Mongoose update issue

I am currently facing a challenge with updating MongoDB using Mongoose. Although there are no error messages, the update process is not taking place even after trying various solutions. exports.update_a_keyValue = function(req, res) { console.log("tem ...

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? ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

Encountered an issue while setting up the MongoDB dependencies for the Node.js application

Looking for assistance with this error message encountered during package installation: "unexpected end of JSON input." You can check out the log file here. Here's a glimpse of the log file while installing the MongoDB package: 0 info it worked i ...

Is there a more efficient method for a logged-in user to trigger a cloud function and retrieve data from Firestore in Firestore?

I manage a website that stores data in Cloud Firestore. In order to keep the database updated with fresh information, I regularly pull data from various APIs and store it. However, my current method of providing users with this real-time data involves thei ...

Issue: Unable to interpret configuration file: ' + fullFilename + ': ' + e3

One of the challenges I faced in my project using express.js was setting up different environments for development, staging, and production. To tackle this issue, I decided to utilize the 'config' module available at https://www.npmjs.com/package ...