提问者:小点点

node js和mongodb中的认证问题


我正在使用这段代码,并且我希望仅当用户存在于MongoDB数据库中时才发送错误消息。问题是当我尝试使用失眠发布一个新用户时,它仍然告诉我它是存在的:当我记录ExistingUser时,它等于[],那等价于true吗?当我调用find the方法而没有记录时,它是否应该返回一个空数组?

让用户=required(“。。/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个答案

匿名用户

在Javascript中,空对象({})需要正确检查空数组([]),如果不正确,则会导致true,如下所示:

null

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