node.js - 无法将属性 'username'设置为null

标签 node.js mongodb express error-handling passport.js

发生错误,登录用户将尝试更新其帐户用户名,但遇到错误。在我的一生中,我无法弄清为什么有时(也许有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查询找不到匹配的用户,则User.findOne({username: req.body.currentUser}将为null(如docs中所述)。
因此,您应该添加另一种检查(如果是这种情况)并进行适当处理:

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

关于node.js - 无法将属性 'username'设置为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63428123/

相关文章:

node.js - 如何使用 Node、Async 和 Mongoose 计算作用域变量的总和?

javascript - Mongo 陷阱 : how can I perform kind of synchronously, 上的异步操作我有正确的逻辑

node.js - 如何将 Blockchain.info 的接收付款 API 与 Node JS/Express 结合使用?

javascript - 如何处理 Express Session?

node.js - For 循环在 Node js 中无法正常工作

javascript - 在 node.js 中获取控制台路径

javascript - Socket.io动态 "on"绑定(bind)

node.js - Gulp-Imagemin 的 EACCES 错误

java - 如何在 spring-data-mongodb 框架中将 BigDecimal 转换为 Double

mongodb - 更新加入 mongoDB。可能吗?