title: How do I solve a problem with my DB connection and require?
body: <p>I have an Express app that was created with express generator. I have a standard <code>app.js</code> file that exports app. I also have a standard <code>www</code> file that imports <code>app</code> and is a starting point of the application:</p>
  <pre><code>const app = require('../app')
  const debug = require('debug')('img-final:server')
  const http = require('http')
  const Mongo = require('../utils/dbConnection/dbConnection')
  const port = normalizePort(process.env.PORT || '3000')
  app.set('port', port)
  
  /**
   * Create HTTP server.
   */
  const server = http.createServer(app)
  
  /**
   * Listen on provided port, on all network interfaces.
   */
  
  async function startServer() {
    try {
      await Mongo.init()
      debug('Connected correctly to DB')
      server.listen(port)
    } catch (err) {
      debug(err)
    }
  }
  
  startServer()
  
  //some more unrelated code. 
  </code></pre>
  <p>I also have a  utility file for connecting to db <code>dbConnection.js</code>:</p>
  <pre><code>const MongoClient = require('mongodb').MongoClient
  
  class Mongo {
    async init() {
      const client = new MongoClient(`mongodb://localhost:27017/img-new`, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      })
      await client.connect()
      this.db = client.db('img-new')
    }
  
    getConnection() {
      return this.db
    }
  }
  
  module.exports = new Mongo()
  </code></pre>
  <p>My problem is that when I start my app <code>const app = require('../app')</code> is obviously running first, and wherever in my app route controllers I use <code>getConnection()</code>, the connection is <code>undefined</code> at that point because my <code>Mongo.init()</code> is running after  <code>const app = require('../app')</code>.</p>
  <p>I'm trying to understand how to solve it in sane way. I guess I can move all <code>require</code>'s and all other code inside <code>startServer</code> after <code>await Mongo.init()</code> , but it seems like there should be a better solution. Thank you.</p>
  <p>Edit:
  Is this an OK solution ?</p>
  <pre><code>const debug = require('debug')('img-final:server')
  const http = require('http')
  const Mongo = require('../utils/dbConnection/dbConnection')
  
  
  
  async function startServer() {
    try {
      await Mongo.init()
  
      const app = require('../app')
      
      const port = normalizePort(process.env.PORT || '3000')
      app.set('port', port)
      const server = http.createServer(app)
      server.listen(port)
  
    } catch (err) {
      debug(err)
    }
  }
  
  startServer()
  </code></pre>