klaurtar
klaurtar

Reputation: 253

Cannot DELETE mongodb entry

I am creating a blog app using node.js/express/mongoose/mongodb. I am creating a delete route so I can delete posts from my admin panel. I am also using method-override to delete. Whenever I press the button I created to delete a post I am met with an error saying cannot DELETE blogs/(blog name here). Not sure why it is not working, and any help would be greatly appreciated.

Here is the Delete route code

//DELETE BLOG ROUTE
app.delete("/blogs/:slug", function(req, res){
  //DESTROY BLOG
  Blog.findOneAndRemove({ slug: req.params.slug}, function(err){
      if(err){
          res.redirect("/admin");
      } else {
          res.redirect("/admin");
      }
  })
});

Here is my button to delete on my admin panel

<div class="d-flex justify-content-between">
                                    <a href="/blogs/<%= blog.slug %>" class="btn btn-primary">View Post</a>
                                    <a href="/blogs/<%= blog.slug%>/edit" class="btn btn-success">Edit Post</a>
                                    <form action="/blogs/<%= blog.slug %>?_method=DELETE" method="POST">
                                        <button class="btn btn-danger"><i class="far fa-trash-alt"></i> Post</button>
                                    </form>
                                </div>

Upvotes: 1

Views: 582

Answers (2)

Najim Ali
Najim Ali

Reputation: 201

In the Delete Route, you are passing slug as parameter so instead of using the blog.slug.

Use slug only. Example:

<div class="d-flex justify-content-between">
  <a href="/blogs/<%=slug %>" class="btn btn-primary">View Post</a>
  <a href="/blogs/<%=slug%>/edit" class="btn btn-success">Edit Post</a>
  <form action="/blogs/<%=slug %>?_method=DELETE" method="POST">
    <button class="btn btn-danger"><i class="far fa-trash-alt"></i> Post</button>
  </form>
</div>

Upvotes: 0

Sai Keerthan
Sai Keerthan

Reputation: 21

use blog._slug instead of blog.slug. Because , mongoose extracts "id" as collections._id

Upvotes: 2

Related Questions