title: Could somebody explain how to pass globally the database variable in express.js?
body: <p>already tried a lot of tutorials, but somehow I could not figure it out.
  I am using mongodb and express.js
  this is in my server.js</p>
  
  <pre><code>const express = require('express');
  const subdomain = require('express-subdomain');
  const bodyParser= require('body-parser');
  const MongoClient = require('mongodb').MongoClient;
  const routes = require('./routes');
  const app = express();
  var db;
  
  app.set('view engine', 'pug');
  
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(express.static('views'));
  app.use(subdomain('api', routes.api));
  
  MongoClient.connect('mongodb://localhost:27017/test', (err, database) =&gt; {
    if (err) return console.log(err);
    db = database;
    app.listen(3000, () =&gt; {
      console.log('listening on 3000');
    });
  });
  </code></pre>
  
  <p>and this is in my routes.js</p>
  
  <pre><code>const express = require('express');
  const api = express.Router();
  
  api.get('/', function (req, res) {
    db.collection('test').find().toArray((err, result) =&gt; {
      if (err) return console.log(err);
      res.render('api_orders', {test: result});
    });
  });
  
  module.exports = {
      api
  }
  </code></pre>
  
  <p>I would like to use the db variable also in routes, but it always gives me the db is not defined error (obviously) I read that I should somehow export the db var, but could not managed to do it</p>