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

Dor*_*ron 5 ejs mongoose mongodb node.js express

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

现在我想在我的一个视图中打印/显示所有用户数据。

在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
    });
});
Run Code Online (Sandbox Code Playgroud)

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

<ul>
<% Users.forEach( function(err, user) { %>
<li><%= user %> </li>
<% }); %>
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:“未定义不是函数”,因为 <% Users.forEach( function(err, user) { %> 行

我究竟做错了什么?

chr*_*dam 3

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

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 });
    }
});
Run Code Online (Sandbox Code Playgroud)

然后在您的 as 中呈现用户文档列表profile.ejs

<% users.forEach(function (user) { %>
    <li>  
        <h1><%= user.name %></h1>  
    </li>                                   
<% }) %>
Run Code Online (Sandbox Code Playgroud)