【发布时间】: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