使用Node.js,Express和Handlebars在导航栏中显示MongoDB文档的字段值

问题描述 投票:0回答:1

我正在构建一个非常简单的应用程序来显示来自MongoDB的信息(使用Mongoose)。

我想在导航栏中显示文档的started字段值。因此必须在每一页上显示。

{
    "_id" : ObjectId("5a4668271f12a77878e97bf1"),
    "started" : 1514563623,
    "discipline" : "coding",
    "isCompleted" : false,
    "date" : ISODate("2017-12-29T16:07:03.340Z"),
    "__v" : 0
}

我试过在Handlebars Helper中创建一个函数。但我经常遇到同样的问题:我可以console.log它,但我不能return它。

我也试过创建一个中间件。它在我的localhost环境中或多或少都可以正常工作,但是当我将它推送到我的生产环境时它不起作用。

var currentLogNavBar = function (req, res, next) {

    // Load Model
    require('./models/Log');
    const Log = mongoose.model('logs');

    Log.findOne({
        isCompleted: false
    })
    .then(logs => {
        res.locals.lastLogSecondsStarted = logs.started || null;
    });
    next()
  }

app.use(currentLogNavBar)

然后在把手navBar中调用它:

{{{lastLogSecondsStarted}}}

我想这个问题与node.js的异步性质有关。

我应该使用其他方法吗?我做错了什么,我怎么能让它发挥作用?

谢谢!

编辑:添加了MongoDB文档的示例。

node.js mongodb express mongoose express-handlebars
1个回答
0
投票

这解决了我的问题:

var currentLogNavBar = function (req, res, next) {

    // Load Model
    require('./models/Log');
    const Log = mongoose.model('logs');

    Log.findOne({
        isCompleted: false
    })
    .then(logs => {
        res.locals.lastLogSecondsStarted = logs.started || null;
        next();
    })
    .catch(err => {
        next(err);
    });

app.use(currentLogNavBar)
© www.soinside.com 2019 - 2024. All rights reserved.