When updating element ,which default value false or null, error occurs TypeError: Cannot read property 'exvariable' of null

When updating element ,which default value false or null, error occurs TypeError: Cannot read property 'exvariable' of null

我正在使用猫鼬开发 nodejs express。每个用户都有例如 exvariable 控制权限有 exvariabletext.

我的用户模型架构 exvariableexvariabletext;
exvariable : {type:Boolean,default:false},
exvariabletext:{type:String,default:null}

当我尝试查找用户并检查 if(user.exvariable === false) 时,我收到类似
TypeError: Cannot read 属性 'exvariable' of null 的错误。所以我不能使用默认值并更新它。

我尝试更改nodejs语法中模式和控制的默认值,但无法通过错误,我想了解其中的逻辑。

我的代码是这样的;

router.post("/setexvariable",(req,res)=>{
    
    User.findById(req.params.id,(err,user)=>{
        if(err){
            console.log(err);
            req.flash("error","Oops, try again ");
            res.redirect("back");
        }
        
        if(user.exvariable == false){
            user.exvariable=true;
            user.exvariabletext=req.body.text;
            user.save();
            req.flash("success","Welcome ");
            res.redirect("/somewhere",{user:user});
        }else{
            req.flash("error","You already has a exvariable ");
            res.redirect("back");
        }
    });
});

您必须在路由中设置 id 参数才能使用 req.params.id 访问它。在您的代码中,req.params.idundefined,因此您的查询 returns null.

你应该有类似 router.post("/setexvariable/:id", (req, res) => {...}) 的东西。 Express's documentation.

中更多关于路由参数的信息