【发布时间】:2020-08-29 17:58:20
【问题描述】:
我正在使用基于 @bradtraversy 教程的 MongoDB 开发 Sails.js CRUD 应用程序(文章管理)。我在尝试使用 EJS 语法和 forEach 循环显示数据库中的文章时遇到了问题。错误提示“未定义文章数据”。 Error image
基本上我通过 Sails /Create?title=ArticleOne%20body=BodyOne URL 蓝图将示例记录传递给 Mongo。在Mongo中可以清楚地看到该文章。 MongoDB article image
datastores.js 是为 Mongo 配置的:
module.exports.datastores = {
mongodb: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'articlebase'
},
};
routes.js 指出 list.ejs 视图:
module.exports.routes = {
'/': { view: 'pages/homepage' },
'/articles/list': { view: 'pages/list' },
'/articles/add': { view: 'pages/add' },
};
Article.js 模型:
module.exports = {
attributes: {
title:{
type: 'string'
},
body:{
type: 'string'
}
},
datastore: 'mongodb'
};
ArticlesController.js
module.exports = {
list:function(req, res){
Articles.find({}).exec(function(err, articles){
if(err){
res.send(500, {error: 'Database Error'});
}
res.view('list', {articles:articles});
});
},
add: function(req, res){
res.view('add');
}
};
最后是麻烦的 list.ejs 视图:
<h1 class="display-4">Articles</h1>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th></th>
</tr>
</thead>
<tbody>
<% articles.forEach(function(article){ %>
<tr>
<td><%= article.id %></td>
<td><%= article.title %></td>
<td>
<a href="/articles/edit/<%= article.id %>" class="btn btn-primary">Edit</a>
<form class="d-inline" action="/articles/delete/<%= article.id %>" method="post">
<input type="submit" value="Delete" class="btn btn-danger">
</form>
</td>
</tr>
<% }); %>
</tbody>
</table>
如何使用 EJS 正确显示来自 MongoDB“文章”集合的文章?提前感谢您的帮助!
【问题讨论】:
标签: mongodb express sails.js ejs sails-mongo