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.