Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display all users database (mongodb) details on .ejs file

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?

like image 793
Doron Avatar asked Oct 17 '22 18:10

Doron


1 Answers

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>                                   
<% }) %>
like image 86
chridam Avatar answered Oct 22 '22 15:10

chridam