I have a mongoDB database in which data is available when I use the ejs command <%=foundAnswer.week%> In the frontend the data gates printed but in the backend it posts error that cannot read null.. even though evrything works fine.
This is my backend route-
app.get('/nptel/:courseName/:weekNumber', function (req, res) {
Nptel.findOne(
{
nptel_name: req.params.courseName,
week: req.params.weekNumber,
},
(err, foundAnswer) => {
if (!err) {
res.render('nptel_weeksAnswer', {
foundAnswer: foundAnswer,
});
} else {
res.render('error');
}
}
);
});
And here is the ejs file –
<div class="col"><h1>Week <%=foundAnswer.week%> :</h1></div>
<div class="nptel_answer mb-2">
<div class="nptelQ"><h4><%=foundAnswer.question_1%></h4></div>
<div class="nptelA"><h5><%=foundAnswer.answer_1%></h5></div>
</div>
Here, is the error –
TypeError: C:UsersparakDesktopMy WebsiteBrogrammersBrogrammersviewsnptel_weeksAnswer.ejs:5
3| <div class="container">
4| <div class="row row-cols-1 row-cols-md-2 g-4">
>> 5| <div class="col"><h1>Week <%=foundAnswer.week%> :</h1></div>
6| <div class="col" style="position: static; bottom: 0%">
7| <h1 style="color: red">
8| Disclaimer :
Cannot read properties of null (reading 'week')
I tried removing the spaces and all .. and checked my data tree .. evrything is fine … and frontend works fine.
2
Answers
I want from you to add the following line to your code:-
Then run your code and give us the result shown in the consle
Be careful if you are using the last version of Mongoose since callbacks are no longer accepted for
findOne
:Make sure to check if
foundAnswer
has actually been found on EJS: