how to define this variable "usersWithSecret is not defined" in app.js?

Viewed 65
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.

2 Answers

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>
<% }) %>

You are rendering undefined value to usersWithSecret, assign "foundUser" to "usersWithSecret". res.render('secrets', {usersWithSecret: foundUser});

Related