title: Export MySQL connection for use with other modules in Node/Express using promise-mysql?
body: <p>Attempting to import and use a database module in one of my controllers. The initial connection is logged, however, I'm receiving the following error when hitting any of my routes from the browser:</p>
  
  <blockquote>
    <p>"Cannot read property 'query' of undefined"</p>
  </blockquote>
  
  <p>The connection variable in the database.js file is obviously not being set, but for the life of me I cannot figure out why.</p>
  
  <hr>
  
  <p>database.js</p>
  
  <pre><code>const mysql = require("promise-mysql");
  const config = require("../config");
  
  let connection;
  
  mysql.createConnection(config.MYSQL)
  .then(conn =&gt; {
    connection = conn
    console.log('Connected to ', config.MYSQL.database)
  })
  .catch(function (error) {
    console.log(error)
  })
  
  module.exports = connection;
  </code></pre>
  
  <hr>
  
  <p>schools.js</p>
  
  <pre><code>const router = require('express').Router()
  const Schools = require('../controllers/schools-controller')
  
  const schools = new Schools
  
  router.get('/', schools.getAllSchools)
  ...
  
  module.exports = router
  </code></pre>
  
  <hr>
  
  <p>schools-controller.js</p>
  
  <pre><code>const db = require("../lib/database");
  
  
  module.exports = class Schools {
  
   async getAllSchools (req, res, next) {
  
    const queryString = 'SELECT * FROM schools ORDER BY school_id ASC LIMIT 5'
  
    try {
      const results = await db.query(queryString);
      if (results == "") {
       res.status(404).json({ message: "No schools found" });
      } else {
        res.status(200).json(results);
      }
    } catch(error) {
      next(error)
    }
   };
   ...
  
  }
  </code></pre>
  
  <hr>
  
  <p><em>Below is the pool function I ended up using based on the answer from @Sven</em></p>
  
  <p>database.js</p>
  
  <pre><code>const pool = mysql.createPool(config.MYSQL);
  pool.getConnection()
    .then(function(connection) {
      console.log(`Connected to database: ${config.MYSQL.database}`);
      pool.releaseConnection(connection)
    })
    .catch(function(error) {
      console.error(error.message);
    });
  
  module.exports = pool;
  </code></pre>