0

I'm creating a website called makeFriend. When user adds a friend, the friend will be saved to the database. After that I got the data from database and set it to the friends variable. In Ejs file I tried to write friends to the screen but I got an EJS Reference error: friend not defined.

Even though I defined "friends" in this function I got error.

        // Friend is the model of my mongo database
    Friend.find({}, function(err, friends){
        if(err){
            console.log(err);
        }else{
            console.log(friends, {friends: friends});
        }
    });
    res.render("site.ejs");
});

I wanted to display datas in my website as list:

<div class="container jumbotron text-center">
    <h1>YOUR FRIENDS WILL BE HERE</h1>
    <%friends.forEach(function(friend){%>
        <li id="friend"><%= friend.name %> - <%= friend.surname %></li>
    <%});%>
</div>

But I got error:

    15| <div class="container jumbotron text-center">
    16|     <h1>YOUR FRIENDS WILL BE HERE</h1>
 >> 17|     <%friends.forEach(function(friend){%>
    18|     <li id="friend"><%= friend.name %> - <%= friend.surname %></li> 
    19|    <%});%>
    20| </div>

friends is not defined
    at eval (eval at compile (/home/guney/simpleWebApp/node_modules/ejs/lib/ejs.js:633:12), <anonymous>:22:7)

Güney
  • 91
  • 2
  • 9

1 Answers1

1

Your EJS program doesn't inherit data from the scope of the function that called render.

You must pass data in explicitly:

res.render("site.ejs", { friends });

You also need to do that somewhere that friends actually exists. See How do I return the response from an asynchronous call?.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335