If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To delete a comment, we first need to create a route for handling the deletion of comments. In the routes folder, create a new file called commentRoutes.js
and add the following code:
javascriptCopy code
const express = require('express');
const router = express.Router({ mergeParams: true });
const { ensureAuthenticated } = require('../config/auth');
const Post = require('../models/Post');
const Comment = require('../models/Comment');
// Delete a comment
router.delete('/:commentId', ensureAuthenticated, async (req, res) => {
try {
const { commentId } = req.params;
const { postId } = req.params;
// Find the comment by id and remove it
const deletedComment = await Comment.findByIdAndRemove(commentId);
// Find the post that the comment belongs to and remove the comment id from its comments array
const post = await Post.findByIdAndUpdate(postId, {
$pull: { comments: commentId },
});
res.status(200).json({ message: 'Comment deleted successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server Error' });
}
});
module.exports = router;
In this file, we first import the necessary modules and models. Then, we define a DELETE
route for deleting a comment. We use the ensureAuthenticated
middleware to ensure that the user is logged in before allowing them to delete a comment.
In the route handler, we extract the commentId
and postId
from the request parameters. We use findByIdAndRemove
to find and remove the comment by its id. We then use findByIdAndUpdate
to find the post that the comment belongs to and remove the comment id from its comments
array using $pull
. Finally, we send a JSON response indicating that the comment was deleted successfully.
Now we need to add this route to our app. In the app.js
file, add the following code:
phpCopy code
const commentRoutes = require('./routes/commentRoutes');
app.use('/posts/:postId/comments', commentRoutes);
This tells our app to use the commentRoutes
for URLs that match the pattern /posts/:postId/comments/*
, where *
can be any string.
With this in place, we can now delete comments by sending a DELETE
request to /posts/:postId/comments/:commentId
, where :postId
is the id of the post that the comment belongs to and :commentId
is the id of the comment to be deleted.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.