Search code examples
expressmongoosepartials

How to use app.locals with .findOne in Mongoose


I want to find the logged in user, and set their info to app.locals so that I can use it in any view.

I'm setting it up in my server.js file like so:

app.use(ensureAuthenticated, function(req, res, next) {
  User.findOne({ _id: req.session.passport.user }, (err, user) => {
    console.log('user\n', user)
    app.locals.logged_in_user = user;
    next();
  })
});

console.log('user\n', user) confirms that the user has been found. Then, I should be able to use this user's info in any partial, such as in my layout.hbs file like so:

Currently, {{logged_in_user}} is logged in.

But, it's not working. The answer here suggested to use res.locals instead, but that didn't work. The example here uses static data, but I need dynamic data since user will depend on who's logged in.

Right now, I have to define the user variable in every route. Is there a way to globally define a user variable that can be used in any partial?


Solution

  • You're using passport judging from the code. The documentation states the following:

    If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

    Therefore you can do the following (or however you want to do it):

    app.use((req, res, next) => {
      res.locals.user = req.user
      next()
    }
    

    This will pass the user object to all requests and the views.