title: How to ensure the Knex connection in nodejs
body: <p>I am using NodeJS, Express, and MySQL for my project and want to use Bookshelf ORM with it. </p>
  
  <p>Bookshelf uses Knex for querying, modeling, and suggests to setup the DB connection through Knex(<a href="http://bookshelfjs.org/#installation" rel="noreferrer">http://bookshelfjs.org/#installation</a>).</p>
  
  <p>I am having trouble in establishing a successful DB connection with Knex. I want to start the server only if DB connection is successful, but it seems like it doesn't offer anything after establishing the connection to do so(no promise or property).</p>
  
  <p>This is the code I have been using.</p>
  
  <pre><code>import _knex from "knex"; // npm install knex --save
  import _bookshelf from "bookshelf"; // npm install bookshelf --save
  
  let knex = _knex({
      client: "mysql",
      connection: {
          host: "127.0.0.1",
          database: process.env.DB,
          user: process.env.DB_USERNAME,
          password: process.env.DB_PASSWORD
      },
      debug: true
  });
  
  let bookshelf = _bookshelf(knex);
  
  module.exports.knex = knex;
  module.exports.bookshelf = bookshelf;
  </code></pre>
  
  <p><strong>More reference:</strong> There is another ORM named Sequelize and it provides <code>sequelize.authenticate()</code> which return Promise and could be used as (<a href="http://docs.sequelizejs.com/en/latest/api/sequelize/#authenticate-promise" rel="noreferrer">http://docs.sequelizejs.com/en/latest/api/sequelize/#authenticate-promise</a>)</p>
  
  <pre><code>sequelize.authenticate()
      .then( () =&gt; {
          console.log("Db successfully connected");
          app.listen(port, () =&gt; console.log(`App started at: ${port}`) );
      })
      .catch( err =&gt; console.log('Unable to connect to the database') );
  </code></pre>
  
  <p>The only solution I can think of is to perform a raw query like <code>USE {DB_NAME}</code> and use its output to decide whether to start the server or not. Is this solution good enough?</p>