无法设置 属性 'username' 为 null
Cannot set property 'username' of null
发生错误,登录用户将尝试更新其帐户用户名,但 运行 出现错误。对于我的生活,我无法弄清楚为什么有时(可能有 1/20 用户 运行 进入此)无法找到当前用户。用户只有登录后才能访问此页面。错误是:
throw er; // Unhandled 'error' event
TypeError: Cannot set property 'username' of null
错误似乎发生在这里:user.username = req.body.username;
router.post("/updateAccount", function (req, res) {
if (req.user) {
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
user.username = req.body.username;
user.save(function (err) {
if (err) {
req.flash("error", "It looks like that email address is taken.");
res.redirect('back')
} else {
req.logout();
req.login(user, function (err) {
if (err) console.log('There was an account error' + err)
req.flash("success", "Your account has been created! Your username is " + user.username);
res.redirect('/results')
});
}
});
});
} else {
res.redirect('/results')
}
});
如果 User.findOne({username: req.body.currentUser}
查询找不到匹配的用户(如 docs 中所述),user
将为 null。
因此,如果是这种情况,您应该添加另一项检查并适当处理:
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
// handle this case as user.username = req.body.username will fail
}
// ... rest of the code
发生错误,登录用户将尝试更新其帐户用户名,但 运行 出现错误。对于我的生活,我无法弄清楚为什么有时(可能有 1/20 用户 运行 进入此)无法找到当前用户。用户只有登录后才能访问此页面。错误是:
throw er; // Unhandled 'error' event
TypeError: Cannot set property 'username' of null
错误似乎发生在这里:user.username = req.body.username;
router.post("/updateAccount", function (req, res) {
if (req.user) {
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
user.username = req.body.username;
user.save(function (err) {
if (err) {
req.flash("error", "It looks like that email address is taken.");
res.redirect('back')
} else {
req.logout();
req.login(user, function (err) {
if (err) console.log('There was an account error' + err)
req.flash("success", "Your account has been created! Your username is " + user.username);
res.redirect('/results')
});
}
});
});
} else {
res.redirect('/results')
}
});
User.findOne({username: req.body.currentUser}
查询找不到匹配的用户(如 docs 中所述),user
将为 null。
因此,如果是这种情况,您应该添加另一项检查并适当处理:
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
// handle this case as user.username = req.body.username will fail
}
// ... rest of the code