Node.js 路由捕获空错误(User.findOne)
我很确定这应该是一个简单的修复方法,但我不知道为什么会发生这种情况,我在这里使用nodejs和mongodb 这就是我正在调用的路由,当我这样做时,它将返回404,其中包含一个空对象。 我确信这不是因为它找不到具有电子邮件地址的用户,因为userFound在这种情况下将为null。但我找不到为什么它直接捕获一个空错误或什么Node.js 路由捕获空错误(User.findOne),node.js,express,mern,Node.js,Express,Mern,我很确定这应该是一个简单的修复方法,但我不知道为什么会发生这种情况,我在这里使用nodejs和mongodb 这就是我正在调用的路由,当我这样做时,它将返回404,其中包含一个空对象。 我确信这不是因为它找不到具有电子邮件地址的用户,因为userFound在这种情况下将为null。但我找不到为什么它直接捕获一个空错误或什么 router.post("/notify", function (req, res) { User.findOne({ email: req.body.email }).
router.post("/notify", function (req, res) {
User.findOne({ email: req.body.email }).then((userFound) => {
const notification = {
type: req.body.type,
title: req.body.title,
description: req.body.description,
};
notification.destination = userFound;
Notification.save(function (err, notification) {
if (err) {
console.log(err);
res.status(500).send();
} else {
res.send(notification);
}
});
})
.catch((error) => {
return res.status(404).json(error);
});
});
对不起,我真的觉得问这个很愚蠢。。提前感谢您的帮助。尝试在回调函数的参数中添加下一步:
router.post(“/notify”,函数(req、res、next){
User.findOne(…)
.catch((错误)=>next(错误));
});
首先,多亏了你们的帮助,我真的做了一件非常愚蠢的事,我实际上调用了Notification.save()
而不是const name,它是Notification.save()
这就是为什么我收到了通知。save不是一个函数
错误您是否尝试过将错误记录到catch块中?我尝试了您的第一条语句,但它返回的是相同的{“message”:{}
下一步我会遇到这个错误TypeError:Notification.save不是一个函数
好吧,至少你现在可以开始排除故障了,对吧?事实上,我现在知道问题出在哪里了!谢谢既然你帮我解决了这个问题,我就把你的答案说成是正确的!谢谢Abderraman。