Sato Sato - 6 months ago 11
Node.js Question

How to create a global function which will access DB in express.js

I use express.js, mongodb, ejs. In the navbar, there's an email icon and will display the count of new emails.


Then I need to add this newEmailCount to every route.

Emails.count({userId: userId, new: true})

my question is in express.js, how can I add a global function that can be executed by every route?


If you want to get the count for every GET requests then you can use following approach

router.get('*', function(req, res, next) {
  res.locals.newEmailCount = Emails.count({userId: userId, new: true})

You need to make sure this is always executed by placing it above all the other routes.

You can then pass res.locals.newEmailCount to your render function which renders HTML file for matched route.

This will work also for application instance level routes handling if that's what you're using.