【发布时间】:2018-09-03 00:02:20
【问题描述】:
我目前正在从事一个 express 项目,我正在使用 knex.js 进行查询和迁移。
我有一段时间没有接触节点所以我有点生疏了。本质上,我正在尝试从我的一张表中选择记录,然后在我的一条路线中调用该函数,然后遍历并将其输出到我的 ejs 模板中。
单元模型
'use strict'
const knex = require('knex')(require('../../knexfile'))
module.exports = function(app) {
this.getAll = function() {
knex.select('id', 'unit_prefix', 'unit_name').from('units').then(function(units) {
return units;
})
}
return this
}
然后在我的 routes.js 文件中:
app.get('/dashboard', ensureAuthenticated, function(req, res) {
// console.log(req.user)
console.log(unitModel.getAll)
res.render('dashboard', { user: req.user, units: unitModel.getAll })
})
如果我console.log 是unitModel.getAll 的结果,我得到[Function]。我已经阅读了 knex 如何使用承诺并且是异步的,但是我仍然没有设法使用其他答案来解决我相当简单的问题。
在我的dashboard.ejs 文件中,我有这个代码:
<h3>Jump to unit:</h3>
<%if (units.length > 0) { %>
<% units.forEach(function(unit) { %>
<div class="dashboard-course-item" tooltip="First year unit, covers the basics of web foundations">
(<%= unit.unit_prefix %>) <%= unit.unit_name %>
</div>
<% }) %>
<% } else { %>
<strong>Currently no units have been created.</strong>
<% } %>
我目前在units 表中有一条记录,并且总是看到Currently no units have been created. 消息。
我需要更改哪些内容才能返回可以在我的 ejs 模板中迭代的数组或对象?
提前致谢!
【问题讨论】:
标签: node.js express ejs knex.js