'how to define this variable "usersWithSecret is not defined" in app.js?
app.get('/secrets', function(req, res){
User.find({'secret': {$ne: null}}, function(err, foundUser){
if(err){
console.log(err);
} else{
if(foundUser){
res.render('secrets', {usersWithSecret: usersWithSecret});
}
}
});
});
<%usersWithSecret.forEach(function(user){ %>
<p class="secret-text"><%=user.secret%></p>
<% }) %>
The "userWithSecret" comes as not defined every time I run this code. How can I defined or declare this variable? Thank you.
Solution 1:[1]
I think you are using ejs template engine and here this is not how express.js works, you have rendered a view name secrets using below code
res.render('secrets', {usersWithSecret: usersWithSecret});
so you can access usersWithSecret varibale inside secrets.ejs file obviously which you need to create(just create a file named secrets.ejs inside views folder) and then the below code will work there
<%usersWithSecret.forEach(function(user){ %>
<p class="secret-text"><%=user.secret%></p>
<% }) %>
Solution 2:[2]
You are rendering undefined value to usersWithSecret, assign "foundUser" to "usersWithSecret".
res.render('secrets', {usersWithSecret: foundUser});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vivek sharma |
Solution 2 | user19060816 |