Reputation: 1601
I need to add new object in mongodb.
step 1 - checking if user already exist
step 2 - if result is empty then then creating new user
Problem I am using try catch syntax so if user doesn't then it jumping to catch block, because await result is null, so that can we prevent result null is jumping to catch block ?
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() });
}
});
Upvotes: 0
Views: 71
Reputation: 11975
Your code doesn't enter catch block because .findOne()
return null. It's because you called user.name
when user
is null. Just change your condition to user && user.name
then it will work as expected.
Upvotes: 3