【问题标题】:Result null jump to catch block in mongoose结果空跳转到猫鼬中的块
【发布时间】:2021-06-16 13:36:44
【问题描述】:

我需要在 mongodb 中添加新对象。

第 1 步 - 检查用户是否已经存在

第 2 步 - 如果结果为空,则创建新用户

问题 我正在使用 try catch 语法,所以如果用户不这样做,它会跳转到 catch 块,因为 await 结果为 null,所以我们可以防止结果 null 跳转到 catch 块吗?

exports.create = async (req, res, next) => {
try {
   // collection 
   user = await User.findOne({ name: name });

   if (user.name) {
     return res.json({ status: 500, message: "already exist"});
   }


   // adding new user 
   let newUser = await User.create({ newUserObject }, { new: true });
   if(newUser) {
    return res.json({ message: "Your account was successfully created! ", status: 200 
    });
   }



} catch(err) {
 res.json({ status: 500, message: err.message || err.toString() });
}
});

【问题讨论】:

  • 如果User.findOne 返回null,这不是错误,它只是一个结果。如果您落入catch 块中,则意味着存在真正的错误。它是什么?消息是什么?你登录了吗?

标签: javascript mongodb express mongoose error-handling


【解决方案1】:

您的代码没有进入 catch 块,因为 .findOne() 返回 null。这是因为当user 为空时,您调用了user.name。只需将您的条件更改为user && user.name,它就会按预期工作。

【讨论】:

    猜你喜欢
    • 2018-07-05
    • 2015-08-04
    • 2018-09-30
    • 2018-08-22
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多