【问题标题】:How to display all users database (mongodb) details on .ejs file如何在 .ejs 文件上显示所有用户数据库(mongodb)详细信息
【发布时间】:2017-06-07 04:54:28
【问题描述】:

我有一个使用本教程构建的 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
    });
});

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

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

我收到一个错误:“未定义不是函数”,因为 行

我做错了什么?

【问题讨论】:

    标签: node.js mongodb express mongoose ejs


    【解决方案1】:

    您需要通过模型的 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 });
        }
    });
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多