title: How to properly pass mysql connection to routes with express.js
body: <p>I am trying to figure out the best way to pass a mysql connection (using node-mysql) between my routes for express.js. I am dynamically adding each route (using a for each file loop in routes), meaning I can't just pass in the connection to routes that need it. I either need to pass it to every route or none at all. I didn't like the idea of passing it to ones that dont need it so I created a dbConnection.js that the routes can individually import if they need. The problem is that I dont think I am doing it correctly. As of now, my dbConnection.js contains: </p>
  
  <pre><code>var mysql = require('mysql');
  var db = null;
  module.exports = function () {
      if(!db) {
              db = mysql.createConnection({
                  socketPath: '/tmp/mysql.sock',
              user: '*********',
              password: '*********',
              database: '**********'
          });
      }
      return db;
  };
  </code></pre>
  
  <p>And I am importing it into each route using:</p>
  
  <pre><code>var db = require('../dbConnection.js');
  var connection = new db();
  </code></pre>
  
  <p>But I would like to do it like this:</p>
  
  <pre><code>var connection = require('../dbConnection.js');
  </code></pre>
  
  <p>When I try it like this, however, I get an error saying connection has no method 'query' when I try to make a query.</p>