【问题标题】:Mongoose error handling for fetching by using findOne使用 findOne 进行获取的 Mongoose 错误处理
【发布时间】:2020-05-15 07:14:04
【问题描述】:

在下面的路线中,我从 url 接收 user_id 并使用 mongoose 从 mongoDb 获取数据。 假设我的 url 看起来像 'http://localhost/user/5eb47018d2ca374ea4cb36431' 我得到了想要的结果。但是,如果我更改像 '5eb47018d2ca374ea4cb36431234' 这样的 id 值,它会返回服务器错误。这是我不想回来的。相反,我喜欢返回“未找到用户”。如何处理 catch 块中的错误以发送所需的消息,例如“找不到用户”。

请原谅错误的英语。

  router.get('/user/:user_id', async(req, res) => {
      try {
          const profile = await Profile.findOne({ user: req.params.user_id }).populate('user', ['name', 
          'avatar']);
          if (!profile) return res.status(400).json({ msg: 'No user for this profile' });
          res.json(profile);
         }catch (err) {
           console.error(err.message);
           res.status(500).send('Server Error');
        }
    });

配置文件表中的数据

_id
:
5eb719425b385c31e475fa0d
skills
:
Array
0
:
"HTML"
1
:
"CSS"
2
:
"JS"
3
:
"PHP"
4
:
"JQUERY"
user
:
5eb47018d2ca374ea4cb3643
company
:
"xxxx"
website
:
"https://xxxx.xyz"
location
:
"xxxx"
bio
:
"Developer of this proect"
status
:
"developer"
githubusername
:
"notspecified"
social
:
Object
facebook
:
"https://facebook.com/xxxx"
twitter
:
"https://twitter.com/xxx"
experience
:
Array
date
:
2020-05-09T20:57:38.178+00:00
__v
:
0

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    try 块内的代码中检查user_id 是否有效ObjectId。如果它不是有效的 Id,它将引发错误。所以把这个if (!mongoose.Types.ObjectId.isValid(req.params.userid)) return res.status(400).json({ msg: 'No user for this profile' }); 放在你的try 块中,如下所示:

      router.get('/user/:user_id', async(req, res) => {
          try {
    
            if (!mongoose.Types.ObjectId.isValid(req.params.userid)) 
                return res.status(400).json({ msg: 'No user for this profile' });
    
              const profile = await Profile.findOne({ user: req.params.user_id }).populate('user', ['name', 
              'avatar']);
              if (!profile) return res.status(400).json({ msg: 'No user for this profile' });
              res.json(profile);
             }catch (err) {
               console.error(err.message);
               res.status(500).send('Server Error');
            }
        });
    

    之前检查参数是否有效 ObjectId,如果它不是有效的 id,则返回所需的响应。如果它是有效的,那么继续检查它的可用性。

    【讨论】:

      【解决方案2】:

      用户的类型是什么?如果收到的 id 与配置文件 id 相同,请尝试使用 _id 而不是用户

      【讨论】:

      • 它是从另一个模式中引用的。一切正常,但是当我将 id 参数从 24 长度更改为其他长度时,它会给出“错误 Cast to ObjectId failed for value XXX at path yy.”。我需要在 catch 块中捕获此错误,以便最后一条语句 'res.status(500).send('Server Error');'不要执行而不是像“找不到用户”这样的发送响应。
      • 实际上它崩溃了,因为它不是一个有效的 MongoDB id,而且你只有一个 catch 块。所以你可以通过在搜索数据库之前检查 id 的长度来解决它,如果它不是有效的 id 你只需发送未找到用户的响应,或者您可以检查 catch 块,如果错误消息 === 错误 Cast to ObjectId failed for value XXX at path yy send no user found而不是服务器错误
      • 感谢它的工作。我使用 if 语句来检查它是否是有效的 id。如果不是有效的 ID,我不会从 mongoDb 查询数据。 if (!mongoose.Types.ObjectId.isValid(req.params.userid)) return res.status(400).json({ msg: 'No user for this profile' });
      猜你喜欢
      • 2012-05-15
      • 2021-12-04
      • 2017-01-11
      • 2012-08-05
      • 2012-12-28
      • 2014-01-07
      • 2021-07-12
      • 2011-09-18
      • 1970-01-01
      相关资源
      最近更新 更多