【问题标题】:Send obj with page render in expressjs mongoose在 expressjs mongoose 中发送带有页面渲染的 obj
【发布时间】:2019-01-27 12:49:23
【问题描述】:

作为这篇文章的后续: mongoose find all not sending callback

我现在尝试在我的 nodejs/expressjs 应用程序中发送一个对象以及一个页面,而不是仅发送 JSON 数据作为响应。

我的页面的路线

//Get latest listings page
router.get('/latest', function (req, res) {
    var rL = Request.getAllRequestListingsCb();
    res.render('latest');
});

根据链接的帖子,它建议以下内容,但我需要将 JSON 返回到我的路线,而不是直接发送给客户端。

//Find all. 
module.exports.getAllRequestListings = function (response) {
    var query = {};
    Request.find(query, function (err, docs) {
        response.send(docs);
    });
};

已尝试使用承诺,但我的 rL var 一直以未定义的形式返回,因此承诺永远不会“完成”,我相信这是因为我没有正确更改它,所以现在在这里。

(最终目标是使用“handlebars”在最新页面中呈现表格,以显示来自 Json 与页面一起发送的数据。)

【问题讨论】:

    标签: javascript node.js express mongoose promise


    【解决方案1】:

    您应该使用正确的回调链接,因为find 方法是异步的。

    //Find all. 
    module.exports.getAllRequestListings = function (callback) {
        var query = {};
        Request.find(query, callback);
    };
    

    路由器

    //Get latest listings page
    router.get('/latest', function (req, res) {
        Request.getAllRequestListingsCb(function (err, docs){
            res.render('latest', { rL: docs });
        });
    
    });
    

    【讨论】:

    • 非常感谢@abskmj,甚至还想出了如何限制广告排序结果。
    猜你喜欢
    • 2015-01-30
    • 2018-03-24
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多