node.js - 检查排序后现有是否不起作用
问题描述
我的 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));
});
});
}
});
});
解决方案
推荐阅读
- c# - 绑定到 UserControl 中 ComboBox 的 SelectedItem
- ios - 如何为 iPhone 获取新的 UDID 以在 Apple 门户中注册
- mysql - 您如何在 MySQL 工作台中为多个 SQL 查询计时?
- html - 如何在具有不同背景颜色的div中间显示文本?
- c# - 如何将值从存储过程控制器输出到 PostMan
- php - 需要在laravel中创建一个下拉列表,并将结果插入到一个新的数据库中
- r - R使用下标和上标创建具有不同标题和轴名称的多个图形
- r - ggplot 扩展图例颜色条
- scala - Spark - 使用 df.schema.copy 函数为另一个数据帧复制一个字段
- branch.io - 有什么方法可以检查 branch.io URL 是否存在?