简体   繁体   English

Mongoose Delete和Express app.delete有什么区别

[英]What is the difference between Mongoose Delete and Express app.delete

I am learning NodeJS and using MongoDB for a database (mongoose to interact). 我正在学习NodeJS并使用MongoDB作为数据库(mongoose进行交互)。 The current course I am doing is only using the mongoose methods to "Delete" and "Update" and using Express to make a "post" request to do it. 我正在做的当前课程只是使用mongoose方法来“删除”和“更新”,并使用Express来发出“发布”请求。 ie: 即:

app.post("/delete", function(req, res){
  //do something
  Item.findByIdAndRemove(item, function(err){
  })
})

But if you check the Express basic routing Docs they suggest using: 但是,如果您检查他们建议使用的Express基本路由文档:

app.delete('/item', function (req, res) {
  res.send('Got a DELETE request at /item')
})

I know everything should be RESTful and using a POST request to make a DELETE request could cause problems, but in this case are they both accomplishing the same thing? 我知道一切都应该是RESTful并且使用POST请求来发出DELETE请求可能会导致问题,但是在这种情况下他们是否都完成了同样的事情? Sorry if this question is newbie or hard to make sense of, It was just something I had noticed while I was reading an article about REST today. 很抱歉,如果这个问题是新手或难以理解的话,这只是我在今天阅读有关REST的文章时注意到的。

It's better practice to use app.delete , rather than app.post , because it reflects the nature of what the endpoint does. 使用app.delete而不是app.post是更好的做法,因为它反映了端点的功能。 It's easier to see you want to DELETE an item in the below code: 您可以更轻松地看到要删除以下代码中的项目:

app.delete("/item", (req, res) => { /* Delete item */ });

But a POST request is used to post a new item to the storage - so it's less clear. 但POST请求用于将新项目发布到存储 - 因此不太清楚。 The only other conventional way is to use a GET request with the method name in the URI (see this video for poor RESTful API practices, this one included). 唯一的另一种传统方法是在URI中使用带有方法名称的GET请求(有关糟糕的RESTful API实践,请参阅此视频 ,其中包括此内容)。

app.get("/delete-item", (req, res) => { /* Delete item */ });

POST is used to add data to the database, while DELETE deletes an items from the database. POST用于向数据库添加数据,而DELETE从数据库中删除项目。 It allows for clearer code and is useful in postman as you can have the same URL but it is a different request so you can have a different response. 它允许更清晰的代码,并且在邮递员中很有用,因为您可以拥有相同的URL,但它是一个不同的请求,因此您可以有不同的响应。

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

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