【问题标题】:handling 404 status in findById method在 findById 方法中处理 404 状态
【发布时间】: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


【解决方案1】:

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

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

这将向客户端发送 404。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多