在 findById 方法中处理 404 状态



我正在node上创建RESTful API.js(express.js + mongoose(。 我有猫鼬模型,它有_id和标题。

当我处理 GET 请求以按_id查找特定对象时,我使用 findById 方法,我想知道如何处理请求的 id 是否错误。换句话说,问题是"如何处理findById方法的404状态"。

我尝试过这样的事情,但没有用:

Blog.findById(id)
.select("_id title")
.exec()
.then(result => {
if (result) {
res.status(200).json({
article: result
});
} else {
res.status(404).json({
message: 'Article was not found'
});
}
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});

当没有对象符合条件时,猫鼬中的Model.findById将返回 null,因此您只需在所有代码之前.then()内放置一个 if 子句

.then(result => {
if(!result) return res.status(404).send('No result found');
// rest of your code here

这将向客户端发送 404。

最新更新