How can fix my EJS reference error: friend(variable) not defined?

46
June 19, 2019, at 5:00 PM

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)
Answer 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?.

READ ALSO
Segfault with Meteor + Passenger + Nginx

Segfault with Meteor + Passenger + Nginx

I have a Meteor app in production with Passenger+Nginx following this guide: https://wwwphusionpassenger

42
html to pdf fit table on A4

html to pdf fit table on A4

im currently using html-pdf which takes my table data and turns it into an pdf

50
node js variables not giving right values on concurrent events

node js variables not giving right values on concurrent events

So I am using nodejs and using redis pubsub mechanism in thatI have subscribed for a particular topic on redis , which when triggered calls a function

54
setInterval() is different between browser and Node

setInterval() is different between browser and Node

The global methods setInterval and setTimeout are different between browser (window) and NodeJS (global)The behavior is quite the same

48