首页 > 解决方案 > 路由捕获空错误 (User.findOne)

问题描述

我很确定这应该是一个简单的解决方法,但我不知道为什么会发生,我在这里使用 nodejs 和 mongodb。

这是我正在调用的路线,当我这样做时,它只是返回 404 和一个空对象。我确定这不是因为它无法找到具有电子邮件地址的用户,因为在这种情况下 userFound 将为空。但我找不到为什么它直接捕获一个空错误或什么?

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);
    });
});

对不起,我真的觉得问这个很愚蠢..提前感谢您的帮助。

标签: node.jsexpressmern

解决方案


尝试在回调函数的参数中添加下一个:

router.post("/notify", function (req, res, next) {
  User.findOne(...)
    .catch((error) => next(error));
});

推荐阅读