I am working on nodejs express with mongoose. Every user has such as exvariable
which controls permission to have exvariabletext
.
My user model schema exvariable
and exvariabletext
;
exvariable : {type:Boolean,default:false},
exvariabletext:{type:String,default:null}
When I am trying to find user and check if(user.exvariable === false)
, I am getting an Error such like that
TypeError: Cannot read property 'exvariable' of null. So I can't use the default value and update it.
I have tried to change the default value in schema and control in nodejs syntax but couldn't pass the error and I want to understand the logic.
And my code like this;
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");
}
});
});
You have to set the id
parameter in your route to be able to access it with req.params.id
. In your code, req.params.id
is undefined
, so your query returns null
.
You should have something like router.post("/setexvariable/:id", (req, res) => {...})
. More on route params in Express's documentation.