简体   繁体   中英

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM