title: Connecting to database in Node.js from routes
body: <p>I'm working on a express server and am having trouble accessing my database from a route file I have set up for users. When I attempt to make a get request I receive this as an error.</p>
  
  <p>"code": "ER_NO_DB_ERROR",
    "errno": 1046,
    "sqlState": "3D000",
    "index": 0</p>
  
  <p>I have been trying to look for a solution online but most of the answers suggest requiring db.js file everywhere which I already do. I have a feeling I need to pass the connection I made in app.js around but I am not sure how to do this. The relevant parts of my files are below. Database login info has been redacted, I do get a successful connection in app.js. I'm fairly new to this so any help would be appreciated, specifically if there is a better way to use the pool implemented in db.js.</p>
  
  <p>app.js</p>
  
  <pre><code>      var express = require('express');
        var path = require('path');
        var favicon = require('serve-favicon');
        var logger = require('morgan');
        var cookieParser = require('cookie-parser');
        var bodyParser = require('body-parser');
  
        var index = require('./routes/index');
        var users = require('./routes/users');
        var mysql = require('mysql')
        var app = express();
        var users = require('./routes/users');
        var media = require('./routes/media');
        var tv = require('./routes/tv');
        var movies = require('./routes/movies');
        var db = require('./db.js')
  
        var connection = mysql.createConnection({
          port: '3306',
          host: '*********************',
          user: '********',
          password: '******'
         })
  
        db.connect(function(err) {
          if (err) {
            console.log('Unable to connect to MySQL.')
            process.exit(1)
          } else {
              console.log('Successfully connected')
            }
          })
  
        app.use('/api', users);
  </code></pre>
  
  <p>models/user.js</p>
  
  <pre><code>    var db = require('../db.js');
      var passwordHash = require('password-hash');
  
  
      exports.getAll = function(done) {
        db.get().query('SELECT * FROM users', function (err, rows) {
          if (err) return done(err)
          done(null, rows)
        })
      }
  </code></pre>
  
  <p>routes/users.js</p>
  
  <pre><code>    var express = require('express');
      var router = express.Router()
      var user = require('../models/user');
      var db = require('../db.js');
  
      //this doesn't prInt anything currently. This is prompting me to believe I         somehow         
      //need to pass a connection object or am using the pool properly.
      console.log(db.get());
  
      router.route('/users').get(function(req, res) {
        user.getAll(function(err, users) {
          if (err) {
             return res.send(err);
           }
           res.json(users);
         });
      });
  </code></pre>
  
  <p>db.js</p>
  
  <p>//this is taken mostly from a tutorial I found online</p>
  
  <pre><code>    var mysql = require('mysql')
        , async = require('async')
  
      var PRODUCTION_DB = 'app_prod_database'
        , TEST_DB = 'app_test_database'
  
      exports.MODE_TEST = 'mode_test'
      exports.MODE_PRODUCTION = 'mode_production'
  
      var state = {
        pool: null,
        //mode: null,
      }
  
      exports.connect = function(done) {
        state.pool = mysql.createPool({
          port: '3306',
          host: '***************',
          user: '*********',
          password: '*******'
          //database: mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
        })
  
        //state.mode = mode
        done()
      }
  
      exports.get = function() {
        return state.pool
      }
  
      exports.fixtures = function(data) {
        var pool = state.pool
        if (!pool) return done(new Error('Missing database connection.'))
  
        var names = Object.keys(data.tables)
        async.each(names, function(name, cb) {
          async.each(data.tables[name], function(row, cb) {
            var keys = Object.keys(row)
              , values = keys.map(function(key) { return "'" + row[key] + "'" })
  
            pool.query('INSERT INTO ' + name + ' (' + keys.join(',') + ') VALUES         (' + values.join(',') + ')', cb)
          }, cb)
        }, done)
      }
  
      exports.drop = function(tables, done) {
        var pool = state.pool
        if (!pool) return done(new Error('Missing database connection.'))
  
        async.each(tables, function(name, cb) {
          pool.query('DELETE * FROM ' + name, cb)
        }, done)
      }
  </code></pre>