![](/img/trans.png)
[英]Displaying data from a Mongodb collection in ejs using Mongoose
[英]Data from mongodb not displaying in view using EJS
我使用貓鼬,並與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>
<%= title%>可以正常工作,但不能正常工作。 如果我使用對象創建自己的數組並使用相同的forEach循環,那么它也可以工作。
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.