skip to Main Content

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


  1. I want from you to add the following line to your code:-

    console.log(foundAnswer);
    
    if (!err) {
            ** Add it here **
            res.render('nptel_weeksAnswer', {
              foundAnswer: foundAnswer,
            });
          } else {
    

    Then run your code and give us the result shown in the consle

    Login or Signup to reply.
  2. Be careful if you are using the last version of Mongoose since callbacks are no longer accepted for findOne:

    app.get('/nptel/:courseName/:weekNumber', async function (req, res) {
        try {
            const foundAnswer = Nptel.findOne({
                nptel_name: req.params.courseName,
                week: req.params.weekNumber,
            });
            res.render('nptel_weeksAnswer', { foundAnswer });
        } catch (err) {
            res.render('error');
        }
    });
    

    Make sure to check if foundAnswer has actually been found on EJS:

    <% if (foundAnswer) { %>
        <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>
    <% } else { %>
        <div>No answer found</div>
    <% } %>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search