Reputation: 123
I am building login system and want to check whether user exists in database and if passwords match. Later one works good but cant figure out first if statement.
try{
const foundUser = await User.find({"username": req.body.username});
if(foundUser === []) // returns false
res.send('user not found')
else if(foundUser[0].password === req.body.password)
res.send('success')
else
res.send('invalid password')
}catch(err){
res.send('Something went wrong', err)
}
When tested using postman i commented out everything below first line (not catch block) and just sent foundUser variable as response. The value i got is []. Now my if statement compares [] === [], returns false and triggers catch block. Why this happens?
Upvotes: 1
Views: 724
Reputation: 2014
find will return array and findOne will return object you can easily check with the length of an array
if (foundUser.length === 0)
and it is going to catch block because your first statement is false and second statement is
if (foundUser[0].password.....
foundUser is empty and you are getting first index object and comparing password
Upvotes: 1