【问题标题】:can't pass mongo population onto ejs page无法将 mongo 人口传递到 ejs 页面
【发布时间】:2017-03-28 05:04:43
【问题描述】:

我一直在使用 mongoose 成功地在 ejs 页面上呈现来自数据库的信息。现在我想渲染在特定对象上填充的信息(通过 mongo 填充)。这甚至可能吗?到目前为止我还没有成功

app.get('/profile', isLoggedIn, function(req, res) {
    Event.find(function(err, services) {
        if (err) return next(err);

        services.forEach(function(service){

            Event
            .findOne({title: service.title})
            .populate('user')
            .exec(function (err, populated) {
                if (err) return handleError(err);
                if(!populated) console.log("failed")
                else {
                    console.log('The creator is ' + populated.user.local.name);
                    service = populated;
                }
            });

        });

        res.render('./partials/profile.ejs', {user: req.user, status: status, badges: badgerinos, services: services}); // load the profile.ejs partial
    });
});

console.log 正确显示了创建者的姓名,但在渲染页面上,用户字段未定义。我究竟做错了什么?

【问题讨论】:

    标签: node.js mongoose ejs


    【解决方案1】:

    您是否对每个事件进行两次查询?如果您尝试列出所有事件并填充用户字段,则应该更快:

    Event
    .find({})
    .populate('user')
    .exec((err, services) => {
        if (err) return next(err);
        //Services are already populated
        res.render('./partials/profile.ejs', {user: req.user, status: status, badges: badgerinos, services: services}); // load the profile.ejs partial
    });
    

    【讨论】:

    • 谢谢,我以类似的方式解决了它
    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多