Reputation: 190
Trying to check if email provided by the user during the registration step already exists in my Mongo Atlas DB. This is the code I have. I get response.status(409) for all emails regardless of whether email exists in DB or it doesn't. Thank you and appreciate any input.
const userExists = await checkIfUserExists(email);
if (userExists) return res.status(409).json(message.fail('User with this email already exists.'));
async function checkIfUserExists(email) {
return User.findOne({ email: email })
.then( () => true)
.catch(() => false);
}
Upvotes: 0
Views: 468
Reputation: 3719
You are returning true even if the user is not found
const userExists = await checkIfUserExists(email);
if (userExists) return res.status(409).json(message.fail('User with this email already exists.'));
async function checkIfUserExists(email) {
const user = await User.findOne({ email });
return !!user;
}
Upvotes: 0
Reputation: 2979
Try this:
async function checkIfUserExists(email) {
return User.findOne({ email: email })
.then(user => user ? true : false)
.catch(() => false);
}
I don't think that mongoose will throw an Error if it can't find a user. It'll just return null or undefined in your callback.
Upvotes: 1