【问题标题】:Pass result of Knex.js select to ejs template将 Knex.js 选择的结果传递给 ejs 模板
【发布时间】: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.logunitModel.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


    【解决方案1】:

    Promises 在它们的 .then 回调函数中异步返回它们的值,如果你返回 Promise 本身,它将返回 undefined,因为在那一刻,Promise 仍未解决。

    要使您的代码正常工作,您应该执行以下操作:

    单元模型

    'use strict'
    const knex = require('knex')(require('../../knexfile'))
    module.exports = function(app) {
    
    this.getAll = function(){
       return new Promise(function(resolve,reject) {
        knex.select('id', 'unit_prefix', 'unit_name').from('units')
         .then(function(units) { resolve(units);})
         .catch(function(error) {reject(error);})
     })
    }
    return this
    }
    

    routes.js

    app.get('/dashboard', ensureAuthenticated, function(req, res) {
        // console.log(req.user)
        unitModel.getAll()
          .then(function(units){        
            res.render('dashboard', { 
             user: req.user, 
             units: units
        })
       })
    })
    

    【讨论】:

    • 感谢您的回答,我正在尝试您的代码,但在路由文件中确实出现了一个错误,上面写着unitModel.getAll is not a function。我能做些什么来解决这个问题?
    • 我的代码中有一个错误,我编辑了我的答案来修复它
    猜你喜欢
    • 2016-12-13
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 2023-03-20
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多