Search code examples
node.jsmongodbexpressmongooseexpress-handlebars

Display a field's value of a MongoDB document in the navigation bar, using Node.js, Express and Handlebars


I'm building a very simple app to display information from MongoDB (using Mongoose).

I want to show the started field value of a document in the navigation bar. So it has to be displayed on every single page.

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

I've tried creating a function inside of a Handlebars Helper. But I usually run into the same problem: I can console.log it, but I can't return it.

I also tried creating a middleware. And it works more or less fine in my localhost environment, but when I push it to my production environment it doesn't work.

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)

And then calling it in the handlebars navBar:

{{{lastLogSecondsStarted}}}

I guess the issue has something to do with the asynchronous nature of node.js.

Should I use another approach? What am I doing wrong and how can I make it work?

Thanks!

EDIT: Added an example of the MongoDB document.


Solution

  • This solved my issue:

    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)