I'm using this code, and I want to send an error message only when the user exists in the MongoDB database.
The problem is when I try to post a new user using insomnia, it still tells me it exists:
when I log existingUser, it is equal to [], is that equivalent to true?
When I call the find the method and there are no records, should it return an empty array?
let User = require('../models/user.model')
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error' + err))
})
router.route('/add').post(async (req, res) => {
try {
const username = req.body.username
const email = req.body.email
const password = req.body.password
const passwordCheck = req.body.passwordCheck
if (!email || !password || !passwordCheck)
// console.log('enter all fields');
return res.status(400).json({ msg: 'please enter all fields' })
if (password.length < 8)
return res.status(400).json({ msg: 'password must be at least 8 characters' })
if (passwordCheck !== password)
return res.status(400).json({ msg: 'Passwords must match' })
console.log(email);
const existingUser = await User.find({ email });
console.log(existingUser);
if (existingUser) {
return res.status(400).json({ msg: ' exist' })
}
else {
return res.status(400).json({ msg: ' not exist' })
}
} catch (e) {
console.log(e);
}
}