【问题标题】:Data from mongodb not displaying in view using EJS来自 mongodb 的数据未使用 EJS 在视图中显示
【发布时间】:2016-03-23 06:21:04
【问题描述】:

我正在使用 mongoose 和 express 以及 EJS。出于某种原因,我在 mongodb 中的数据没有出现在视图中。我没有收到任何错误,它只是空白。

var Person = require('.././schema.js');

module.exports = function(app) {
app.get('/about', function(req, res) {

var peopleList = [];
var title = "Users in Database:";

Person.find(function (err, people) {
  if (err) return console.error(err);
  for(var i = 0; i < people.length; i++) {
    peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
  }

  console.log(peopleList);
  console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
});

res.render('pages/about', {
  peopleList: peopleList,
  title: title
});
});
}

在我看来:

<h3><%= title %></h3>
<blockquote>
<ul>
<% for(var i = 0; i < peopleList.length; i++) { %>
  <li><%= peopleList[i].name %> : <%= peopleList[i].role %> : <%= peoplelist[i].wage %></li>
<% }; %>
</ul>

替代尝试:

<ul>
  <% peopleList.forEach(function(peopleList) { %>
      <li><%= peopleList.name %> - <%= peopleList.role %></li>
  <% }); %>
</ul>

工作得很好,只是数据不行。如果我创建自己的包含对象的数组并使用相同的 forEach 循环,它也可以工作。

【问题讨论】:

    标签: node.js mongodb express ejs


    【解决方案1】:
    var Person = require('.././schema.js');
    
    module.exports = function(app) {
    app.get('/about', function(req, res) {
    
    var peopleList = [];
    var title = "Users in Database:";
    
    Person.find(function (err, people) {
      if (err) 
        return console.error(err);
    
      for(var i = 0; i < people.length; i++) 
      {
        peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
      }
    
      console.log(peopleList);
      console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
    
      res.render('pages/about', {
      peopleList: peopleList,
      title: title
    });
    
    });
    
    });
    }
    

    请将您的代码更改为此。

    注意:你应该把res.render放在Person.find的回调函数中。

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      相关资源
      最近更新 更多