首页 > 解决方案 > 检查排序后现有是否不起作用

问题描述

我的 mongoDB findOne 之前正在工作,因为它负责检查我的数据库中是否存在电子邮件,但是一旦我将 .sort 添加到它,它就会引发错误UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'email' of null at User.findOne.sort.then.user但是如果我删除排序,它会再次工作,包括电子邮件确实存在验证。

这是代码

router.post('/register', (req, res) => {
  const { errors, isValid } = validateRegisterInput(req.body);

  // Check Validation 
  if (!isValid) {
    return res.status(400).json(errors);
  }

  User.findOne({ email : req.body.email }).sort({unitNo : -1}).then(user => {
    if (user.email === req.body.email) {
    errors.email = 'Email already exists';
     return res.status(400).json(errors);
    } else {
      // create my secret token for email verification
        const secretToken = randomstring.generate();
        const defaultNo = user[0].unitNo;
        const unitNo = String(Number(defaultNo)+1).padStart(4, '0');
        const newUser = new User(
      {
        email: req.body.email,
        password: req.body.password,
        phone : req.body.phone,
        fullname: req.body.fullname,
        secretToken,
        unitNo,
        });
      const DOMAIN = "******.mailgun.org";
      const mg = mailgun({apiKey: "*******", domain: DOMAIN});
      const data = {
                    from: 'no-reply@yourwebapplication.com', 
                    to: newUser.email,
                    subject: 'Account Verification Token', 
                    text: 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '/\api/users/verify\/' + newUser.secretToken + '.\n' 
                   };
      mg.messages().send(data, function (error, body) {
    console.log(body);
});
     bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
            newUser 
             .save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
        });
      });
    }
  });
});

标签: node.jsmongodb

解决方案


推荐阅读