Rosan Paudel
Rosan Paudel

Reputation: 170

Cannot read properties of undefined (reading 'id') in Nodejs

Hi I am trying to make todo app with help of node and express. Everything works fine in frontend but it is showing this error in the terminal. I have passed todo object though it is showing id as undefiened.

my show route in server

  //Fake Database 
let todos = [
    {
        id: uuid(),
        todo: 'Listening to Mozart'
    }
  
]

app.get('/:id', (req, res)=>{
    const {id} = req.params;
    const todo = todos.find(todo => todo.id == id);
    res.render('show', {todo: todo});

My show.ejs file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<%- include ('_styles.ejs') %> 
<%- include ('_new_styles.ejs') %> 

<body>
   <div class="container">
    <div class="card">
        <div class="card-body">
            <h2>ID:<%= todo.id %> </h2>
            <p class="todo-details">
                <%= todo.todo %> 
            </p>
        </div>
    </div>
    <div class="home-btn">
        <a href="/"><i class="fas fa-home"></i></a>
    </div>
   </div>
    <div class="blue-ball"></div>
    <div class="red-ball"></div>
</body>
</html>

Error is:

TypeError: /home/linux/Desktop/todo/views/show.ejs:16
14|     <div class="card">
15|         <div class="card-body">
>> 16|             <h2>ID:<%= todo.id %> </h2>
17|             <p class="todo-details">
18|                 <%= todo.todo %>
19|             </p>

Cannot read properties of undefined (reading 'id')
at eval ("/home/linux/Desktop/todo/views/show.ejs":18:31)
at show (/home/linux/Desktop/todo/node_modules/ejs/lib/ejs.js:692:17)
at tryHandleCache (/home/linux/Desktop/todo/node_modules/ejs/lib/ejs.js:272:36)
at View.exports.renderFile [as engine] (/home/linux/Desktop/todo/node_modules/ejs/lib/ejs.js:489:10)
at View.render (/home/linux/Desktop/todo/node_modules/express/lib/view.js:135:8)
at tryRender (/home/linux/Desktop/todo/node_modules/express/lib/application.js:640:10)
at Function.render (/home/linux/Desktop/todo/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/home/linux/Desktop/todo/node_modules/express/lib/response.js:1017:7)
at /home/linux/Desktop/todo/server.js:38:9
at Layer.handle [as handle_request] (/home/linux/Desktop/todo/node_modules/express/lib/router/layer.js:95:5)

Upvotes: 0

Views: 2721

Answers (1)

Ivan Galan
Ivan Galan

Reputation: 301

Are you sure todos.find(todo => todo.id == id); is returning any match?

Upvotes: 1

Related Questions