admin管理员组文章数量:814911
用于使用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
本文标签: 用于使用findOne进行抓取的猫鼬错误处理
版权声明:本文标题:用于使用findOne进行抓取的猫鼬错误处理 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1715139712a821486.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论