I have a node.js website that i build with this tutorial: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
now i want in one of my views to print/display all users data.
in routes.js:
var User = require('../app/models/user'); //the connection to users database
app.get('/profile', isLoggedIn, function (req, res) {
    res.render('profile.ejs', {
        Users: User // get the user out of session and pass to template
    });
});
and this is in my profile.ejs file:
<ul>
<% Users.forEach( function(err, user) { %>
<li><%= user %> </li>
<% }); %>
i get an error: "undefined is not a function" because of the <% Users.forEach( function(err, user) { %> line
what am i doing wrong?
You need to actually query the user collection via the model's find() query function which will return an array of user documents when executed, i.e.
var User = require('../app/models/user'); //the connection to users database
app.get('/profile', isLoggedIn, function (req, res) {
    User.find({}).exec(function(err, users) {   
        if (err) throw err;
        res.render('profile.ejs', { "users": users });
    }
});
then render the list of user documents in your profile.ejs as:
<% users.forEach(function (user) { %>
    <li>  
        <h1><%= user.name %></h1>  
    </li>                                   
<% }) %>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With