结果空跳转到猫鼬中的catch块

Result null jump to catch block in mongoose

我需要在 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() });
}
});

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