Steps for eliminating an item from an array in MongoDB

I have been struggling with the functionality of the Mongoose library, specifically the remove method. On my webpage, I display comments and have a form with a Delete button. My objective is to delete only the comment that was clicked. Below is an excerpt from my MongoDB file (I utilize the override method from the express library to manage both post and delete requests).



{
    "_id": {
        "$oid": "5a455cf460414f548f3d1afb"
    },
    "title": "Test",
    "body": "test",
    "user": {
        "$oid": "5a440bae124b7e4626aeeb70"
    },
    "date": {
        "$date": "2017-12-28T21:07:00.194Z"
    },
    "comments": [
        {
          "commentBody": "test",
          "commentUser": {
                "$oid": "5a440bae124b7e4626aeeb70"
            },
            "_id": {
                "$oid": "5a455cf660414f548f3d1afc"
            },
            "commentDate": {
                "$date": "2017-12-28T21:07:02.143Z"
            }
        }
    ],
    "allowComments": true,
    "status": "public",
    "__v": 1
}

My Schema



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const StorySchema = new Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    status: {
        type: String,
        default: 'public'
    },
    allowComments: {
        type: Boolean,
        default: true
    },
    comments: [{
        commentBody: {
            type: String,
            required: true
        },
        commentDate: {
            type: Date,
            default: Date.now
        },
        commentUser: {
            type: Schema.Types.ObjectId,
            ref: 'users'
        }
    }],
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    date: {
        type: Date,
        default: Date.now
    }
});

mongoose.model('stories', StorySchema, 'stories');

My JavaScript file, the post method works as expected but the delete method is not functioning (error: Cannot read property 'comments' of undefined)



router.post('/comment/:id', (req, res) => {
    Story.findOne({
        _id: req.params.id
    })
    .then(story => {
        const newComment = {
            commentBody: req.body.commentBody,
            commentUser: req.user.id
        }

        // Add new comment to the comments array
        story.comments.unshift(newComment);

        story.save()
        .then(story => {
            res.redirect(`/stories/show/${story.id}`);
        })
    });
})

router.delete('/comment/:id', (req, res) => {
    Story.remove({
        _id: req.body.id.comments
    })
    .then(() => {
        req.flash('success_msg', 'Comments Removed!');
        res.redirect('/dashboard');
    })
});

Below is my handlebars file with the form

<form action="/stories/comment/{{id}}?_method=DELETE" method="post" id="delete-form">
<input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn red"><i class="fa fa-remove"></i> Delete</button>
</form>

{{/each}}

The error message I am encountering is:

TypeError: Cannot read property 'comments' of undefined
at router.delete (/Users/ar2z/Desktop/fierce-caverns-70427/routes/stories.js:197:20)

I would greatly appreciate any assistance as I am feeling completely lost.

Answer №1

Recently, I came across a similar issue and managed to resolve it successfully by following these steps:

router.delete("/comments/:id", function(req,res){
   var myModel = require("myModel");
   //Execute a find and update query to remove the comment
   myModel.findOne({_id:req.params.id}, function(err,doc){
      if(doc && !err){
         doc.comments = doc.comments.filter(function(comment){
            //Filter out the specific comment to be deleted
            return comment._id != req.body.commentId
         })
      }
      res.redirect("/comments/")
   })
}

Answer №2

My mistake occurred right from the start when I attempted to manipulate an array element in the same manner as I would with a Mongo object.



    Story.remove({
            _id: req.body.id.comments
        })

The above code does not work for array elements; it works for objects. To delete an element from an array, I use the following:



Story.update( { }, { $pull: { comments: { _id: req.params.id }}}, { multi: true } )

This code is used to remove items from an array of documents.

$pull MongoDb documentation

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

Tracking the progress of an AJAX call with a progress bar or progress status

Using an ajax call, I want to display progress status inside a text box. Below is the code for the ajax call: <input type="text" name="cm" id="cm" /> <script type="text/javascript" language="javascript"> $('#cm').blur(function() ...

When access to Ajax .responseText in an alert it can be displayed, however it cannot be stored in a variable or

var response_var=""; // Added for debugging purposes ajax.onreadystatechange = function() { if (ajax.readyState == 4 & ajax.status == 200) { response_var = ajax.responseText; alert(ajax.responseText); // This alerts properly (some text ...

Sharing socket data between different namespaces in Socket.ioSocket.io enables the

Is there a solution to sharing data set in a socket in one namespace and accessing it on another namespace? While I understand that data can be attached to the socket object itself, a problem arises when trying to access the data in a different namespace. ...

Empty req.body in Node.js when POST method is used

I'm completely new to exploring REST and Express, and I've been following this insightful tutorial on creating a REST API. Here's a glimpse of my programming journey through the lens of my app.js code: var express = require('express&ap ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Unable to preserve special characters in express js route URL request

When attempting to retrieve a record from the database using the criteria: VITAMINS + ZINC 100MG/10MG PER 5ML SYRUP The request URL appears as follows: http://localhost:4200/api/search?key=VITAMINS%20+%20ZINC%20100MG/10MG%20PER%205ML%20SYRUP This is wha ...

The issue arises when attempting to render an SVG with JavaScript embedded inside using the img, object, or

Issue with the title ... please follow these steps: (view codes below) Create an svg + open it separately (name it keysaway.svg) Create html + open it individually When you observe, the svg displays a simple up and down animation but fails to work when l ...

Is there a way to link a Google Cloud MySQL database to a React application?

I currently have a MySQL database hosted on Google Cloud Platform. I am seeking advice on the best approach to connect this database with my ReactJS application in order to execute SQL queries and display the results on the screen. Thus far, I haven't ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

jQuery not being applied to dynamically added dropdown element

I am currently utilizing bootstrap and jquery within my react project. I have a button that, when clicked, should transform into a dropdown field. The dropdown functions properly when placed statically, but the functionality is lost once it is dynamically ...

Save data on a mongodb database or server

I am facing a challenge with my MongoDB website where users need to download files other than images, such as software installers like .exe or .msi files, or even Blender files. How can I efficiently store these diverse file formats on the server for eas ...

Is there a way to determine the path of the fetch function within a PHP file?

I am using a JavaScript function to retrieve data from the backend server async getAllExpensesByUser() { let response = await fetch("router.php/getAll"); return response.json(); } My question is, how can I retrieve the path "/getAll ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

An element in defaultProps deemed as nonexistent

As I dive into routes and routing practice, I've encountered some challenges that have me stumped. The issue seems to be in the render method in App.js. The concept is simple - I'm working on a getDogFunc function that should help me locate a s ...

Tips for creating a highly adaptable code base- Utilize variables

Can anyone help me optimize this lengthy and cumbersome code in HTML and JS? I want to make it more efficient by using variables instead of repeating the same code over and over. In the HTML, I've used href links to switch between different months, w ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

Every time I attempt to submit data, I encounter a 404 error with AXIOS

Struggling to figure out why I keep encountering an error when trying to send form data from my website to the database using axios? Despite attempting various solutions, the problem persists. Although I can successfully retrieve manually entered data from ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...