我的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));
});
});
}
});
});