简体   繁体   English

删除请求(MongoDB、express、handlebars)

[英]DELETE REQUEST (MongoDB, express, handlebars)

I am having trouble making a delete request in my application.我在我的应用程序中发出删除请求时遇到问题。 I have a database of reviews, which I alter with my application.我有一个评论数据库,我会根据我的应用程序对其进行更改。

I am trying to make a function that will delete a document from my database and redirect the user to another page.我正在尝试制作一个 function 它将从我的数据库中删除一个文档并将用户重定向到另一个页面。

Here is my handelbars view(i am trying to set it up so if a user clicks on the link, it will excecute the delete method):这是我的 handelbars 视图(我正在尝试将其设置为如果用户单击链接,它将执行删除方法):

<h1>{{rev.title}}</h1>
<h2>{{rev.snippet}}</h2>
<p>{{rev.body}}</p>

<a class ="rem" data-method="delete" href="/reviews/{{this.id}}" >Delete</a>
 //some javascript??!!

This is my router in the routers file:这是我在路由器文件中的路由器:

router.delete('/:id',reviewController.review_delete);

This is my method in the controller file:这是我在controller文件中的方法:

const review_delete =  (req, res) => {
    const id = req.params._id;
    mySchemas.reviews.findByIdAndRemove(id, function (err){
        if(err) {
            res.send(err);
        } else {
            res.redirect("./reviews");
        }
    });

}

I've tried multiple things, but i do not yet understand how to actually make it so that the user can delete things.我已经尝试了很多东西,但我还不明白如何实际制作它以便用户可以删除东西。 Thanks for your help.谢谢你的帮助。

Instead of doing this而不是这样做

 <a class ="rem" data-method="delete" href="/reviews/{{this.id}}" >Delete</a>

Do this做这个

<a class ="rem" href="/reviews/{{this.id}}" onclick="delete({{this.id}})" >Delete</a>
 function delete(id) {
   const xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
     // some code
   };
   xhttp.open("DELETE", `<your-server-host>/reviews/${id}`, true);
   xhttp.send();
 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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