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:
"Cannot read property 'query' of undefined"
The connection variable in the database.js file is obviously not being set, but for the life of me I cannot figure out why.
database.js
const mysql = require("promise-mysql");
const config = require("../config");
let connection;
mysql.createConnection(config.MYSQL)
.then(conn => {
connection = conn
console.log('Connected to ', config.MYSQL.database)
})
.catch(function (error) {
console.log(error)
})
module.exports = connection;
schools.js
const router = require('express').Router()
const Schools = require('../controllers/schools-controller')
const schools = new Schools
router.get('/', schools.getAllSchools)
...
module.exports = router
schools-controller.js
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)
}
};
...
}
Below is the pool function I ended up using based on the answer from @Sven
database.js
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;