Question about authentication in node js and mongodb

Viewed 40

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);
  }
}
1 Answers

In Javascript empty objects ({}) an empty array ([]) need to be checked properly if not they result in true like below:

if([]) console.log('should not be logged this sentence for empty array');
if({}) console.log('should not be logged this sentence for empty object');

The best way to check for these is as below:

// for array values
 arr = typeof(arr) === 'object' && arr instanceof Array ? arr : [];
 // for objects
 obj = typeof(obj) === 'object' && obj !== null ? obj : {};

you just need to verify the existingUser is a valid array with at least one value.

const userExists = (typeof (existingUser) === 'object' && existingUser instanceof Array && existingUser.length > 0);

if (userExists) {
  return res.status(400).json({ msg: ' exist' })
}
else {
  return res.status(400).json({ msg: ' not exist' })
}
Related