如果这不是一种常见的做法,请随时告诉我 - 我是一个相当新的程序员 - 但我想我过去见过 API,当你向资源提交 DELETE 请求时(/todo/1234),有些服务器会在响应中返回你刚刚删除的对象。那是一回事吗?如果是这样,我会对学习如何做感兴趣。这是我拥有的:
.delete(function (req, res) {
Todo.findById(req.params.todoId).remove(function (err) {
if (err) res.status(500).send(err);
res.send("Todo item successfully deleted");
});
});
这段代码确实删除了该项目,但我想在响应中返回被删除的项目而不是字符串消息。如果这是正常/好的事情。如果由于某种原因不正常或不正常,请告诉我原因,我将继续前进。或者也许有更常见的方法。
这是我在 [RFC 7231 文档][1] 中找到的内容:
If a DELETE method is successfully applied, the origin server SHOULD send a 202 (Accepted) status code if the action will likely succeed but has not yet been enacted, a 204 (No Content) status code if the action has been enacted and no further information is to be supplied, or a 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.
我很难理解 200 响应的含义 - 发送字符串消息(成功!
)或包含消息属性的对象({message :“成功!”
)?或者你可以在那里做任何你想做的事吗?在 Express 中使用 Mongoose 的最佳实践是什么?
在此先感谢您的帮助,对于我对 HTTP 内容的笨拙感到抱歉。 [1]: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5
最佳答案
你应该使用 findOneAndRemove !像这样的东西:
Todo.findOneAndremove({ id: req.params.todoId }, function( error, doc, result) {
// it will be already removed, but doc is what you need:
if (err) res.status(500).send(err);
res.send(doc.id);
});
关于node.js - 如何让 Express 返回我刚刚在 MongoDB 中删除的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070236/