Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

How to Delete Comment from Post on Node, express and Mongoose and Ajax

// How to Delete Comment from Post on Node, express and Mongoose and Ajax

You need to know both the postId and the commentId to be able to delete the comment from posts collection. Also it would be good to delete the comment inside the comments collection.

So change your delete route to include postId and commentId as req.params. You can delete a comment from posts using the findByIdAndUpdate method and $pull operator.

router.delete("/comments/:postId/:commentId", async function (req, res) {
  try {
    const post = await Post.findByIdAndUpdate(
      req.params.postId,
      {
        $pull: { comments: req.params.commentId },
      },
      { new: true }
    );

    if (!post) {
      return res.status(400).send("Post not found");
    }

    await Comment.findByIdAndDelete(req.params.commentId);

    res.send("Success");
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});
TEST

Let's say we have this post document with 3 comments.

Posts:

{
    "_id" : ObjectId("5e8b10c49ae619486094ed10"),
    "comments" : [
        ObjectId("5e8b104f9ae619486094ed0d"),
        ObjectId("5e8b10599ae619486094ed0e"),
        ObjectId("5e8b105e9ae619486094ed0f")
    ],
    "title" : "Title",
    "description" : "Description...",
    "from" : "From",
    "postImage" : "Post Image",
    "createdAt" : ISODate("2020-04-06T14:21:40.884+03:00")
}
Comments:

{
    "_id" : ObjectId("5e8b105e9ae619486094ed0f"),
    "message" : "Comment 3"
},

{
    "_id" : ObjectId("5e8b10599ae619486094ed0e"),
    "message" : "Comment 2"
},
{
    "_id" : ObjectId("5e8b104f9ae619486094ed0d"),
    "message" : "Comment 1"
}
If we want to delete the comment with _id:5e8b10599ae619486094ed0e, we need to send a DELETE request to our route using url like this:

http://localhost:3000/posts/comments/5e8b10c49ae619486094ed10/5e8b10599ae619486094ed0e
5e8b10c49ae619486094ed10 is the postId, 5e8b10599ae619486094ed0e is the commentId.

Result will be like this:

Posts:

{
    "_id" : ObjectId("5e8b10c49ae619486094ed10"),
    "comments" : [
        ObjectId("5e8b104f9ae619486094ed0d"),
        ObjectId("5e8b105e9ae619486094ed0f")
    ],
    "title" : "Title",
    "description" : "Description...",
    "from" : "From",
    "postImage" : "Post Image",
    "createdAt" : ISODate("2020-04-06T14:21:40.884+03:00")
}
Comments:

{
    "_id" : ObjectId("5e8b105e9ae619486094ed0f"),
    "message" : "Comment 3"
},
{
    "_id" : ObjectId("5e8b104f9ae619486094ed0d"),
    "message" : "Comment 1"
}
Share
Follow
answered Apr 6 '20 at 11:37

SuleymanSah
12.8k55 gold badges1717 silver badges4242 bronze badges
1
@SuleymanSahThank you so much for taking your time to explain to me how it works, i really appreciate it. I did exactly what you said with the code you gave me above, and changed my link to include post id like this ` <a class="delete-comment" href="#" data-id="<%=post.id%>/<%=item._id%>">Delete</a> ` and everything is – Chukwuma Kingsley Apr 6 '20 at 11:58
Comment

PREVIOUS NEXT
Code Example
Javascript :: show conditional header based on url in vue js 
Javascript :: loader service show hide unit test angular 
Javascript :: python to javascript converter online 
Javascript :: cheatsheet addeventlistener 
Javascript :: contries code react native 
Javascript :: jquery intermediate value eror 
Javascript :: javascript remove last charcter from string 
Javascript :: attach a generated pdf to a smtpjs mail in js 
Javascript :: warn user before leaving page angular 
Javascript :: convert jquery code to javascript online 
Javascript :: create pair foreach item in array 
Javascript :: hypotenuse rectangle triangle javascript 
Javascript :: predicate logic solver 
Javascript :: jquery on scroll x pixels 
Javascript :: node.js wikipedia api call 
Javascript :: valueof in react native 
Javascript :: break string to array javascript without delimeter 
Javascript :: javascript runne 
Javascript :: find first and last occurence in knockout js template 
Javascript :: chrome extension how to save data to an alternative file 
Javascript :: mongodb js get id of inserted 
Javascript :: super slider js 
Javascript :: add cloudinary to gatsby javascript 
Javascript :: redblobgames pathfinding 
Javascript :: expect vue test utils compare objects 
Javascript :: change dxform label angular 
Javascript :: express js continous GET /json/version 
Javascript :: variables 2 python .Bartolome sintes Marco 
Javascript :: puppeteer js onblur 
Javascript :: image image using next and previous button in javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =