如何在 .ejs 文件中显示所有用户数据库 (mongodb) 的详细信息

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

我有一个 node.js 使用本教程构建的网站: https://scotch.io/tutorials/easy-node-authentication-setup-and-local

现在我想在我的观点之一中 print/display 所有用户数据。

在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
    });
});

这是在我的 profile.ejs 文件中:

<ul>
<% Users.forEach( function(err, user) { %>
<li><%= user %> </li>
<% }); %>

我得到一个错误:"undefined is not a function" 因为 <% Users.forEach( function(err, user) { %> line

我做错了什么?

您需要通过模型的 find() 查询函数实际查询用户集合,该函数在执行时将 return 一组用户文档,即

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

然后将您的 profile.ejs 中的用户文档列表呈现为:

<% users.forEach(function (user) { %>
    <li>  
        <h1><%= user.name %></h1>  
    </li>                                   
<% }) %>