【发布时间】:2019-01-24 20:29:17
【问题描述】:
我正在 node.js (express.js + mongoose) 上创建 RESTful API。 我有 _id 和 title 的猫鼬模型。
当我处理 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
});
});
【问题讨论】:
-
错误是什么?另外,您的第一个
.then中的result是什么?
标签: node.js rest api express mongoose