最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

用于使用findOne进行抓取的猫鼬错误处理

网站源码admin20浏览0评论

用于使用findOne进行抓取的猫鼬错误处理

用于使用findOne进行抓取的猫鼬错误处理

在下面的路由中,我从URL接收user_id,并使用mongoose从mongoDb中获取数据。假设我的网址看起来像“ http://localhost/user/5eb47018d2ca374ea4cb36431”,那么我得到了想要的结果。但是,如果我更改ID值,例如“ 5eb47018d2ca374ea4cb36431234”,则会返回服务器错误。这就是我不想返回的内容。相反,我想返回“找不到用户”。如何处理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
:
""
location
:
"xxxx"
bio
:
"Developer of this proect"
status
:
"developer"
githubusername
:
"notspecified"
social
:
Object
facebook
:
""
twitter
:
""
experience
:
Array
date
:
2020-05-09T20:57:38.178+00:00
__v
:
0
回答如下:

用户类型是什么?如果收到的ID与个人资料ID相同,请尝试使用_id代替user

发布评论

评论列表(0)

  1. 暂无评论