illcrx illcrx - 9 days ago 7
Node.js Question

EJS variable showing as null

I have a node/express/ejs application and when I go to the page it shows that the variable has

null
value. Here is the route.

router.get("/events", isLoggedIn, function(req,res){
User.findById(req.params.id).populate("moments").populate("events").exec(function(err,allEvents){
if(err){
console.log(err);
console.log("Ummm.... the database may be down?.......")
} else {
if (allEvents === null){
res.redirect("/dashboard");
} else {
console.log("Below are all the events pulled");
console.log(allEvents)
res.render("eventsList", {events: allEvents});
}
}
});
});


So events is the variable I am passing into "eventsList". The console.log above the render shows events, and when I make a new event it appends to that list. However everytime it goes to the /dashboard page as if there were null in allEvents.

Here is the code on the client side:

<% events.forEach(function(events){ %>


Im gessing it something to do with the if statement, but I cant figure it out.

Answer

Maybe you haven't specified the userId parameter in your route

router.get("/events/:userId",  isLoggedIn, function(req,res){
console.log("userId: ", req.params.userId)   
User.findById(req.params.userId).populate("moments").populate("events").exec(function(err,allEvents){
    if(err){
        console.log(err);
        console.log("Ummm.... the database may be down?.......")
    } else {
        if (allEvents === null){
            res.redirect("/dashboard");
        } else {
        console.log("Below are all the events pulled");
        console.log(allEvents)
        res.render("eventsList", {events: allEvents});
        }
    }
})
});