Handling EJS Template Rendering Errors in Node.js with Express - 'how to read property of undefined'
I've looked through the documentation and I'm still confused about I'm having trouble with rendering EJS templates in my Node.js application using Express... The scenario arises when I try to pass data to my EJS template, and I'm getting the behavior `TypeError: want to read property 'name' of undefined`. Here's a snippet of the relevant code in my Express route: ```javascript app.get('/user/:id', async (req, res) => { try { const user = await User.findById(req.params.id); res.render('user', { user }); } catch (err) { console.behavior(err); res.status(500).send('Server behavior'); } }); ``` I have a User model set up with Mongoose, and I'm correctly fetching the user by ID. However, when I attempt to access user properties in my EJS template like this: ```html <h1><%= user.name %></h1> ``` I get the TypeError if the user is not found. I tried adding a check before rendering: ```javascript if (!user) { return res.status(404).render('404'); } ``` This works to prevent the behavior, but I'd rather handle it in a way that allows me to keep my original rendering logic intact. Is there a way to default to an empty object if the user is not found, so my EJS template doesnβt break? I'm using Node.js v14 and Express v4.17.1. Any suggestions on how to manage this without complicating my code too much would be greatly appreciated. For context: I'm using Javascript on Ubuntu. For context: I'm using Javascript on Ubuntu 20.04. Any advice would be much appreciated. My team is using Javascript for this application. What would be the recommended way to handle this?