title: Database Connection using common module is not working [ mongoose and mongodb ]
body: <p>I am trying to <strong>implement a common module for MongoDB connection using mongoose</strong>. and want to use the connection in other application for database operation. but facing issue when trying to use common database module. operation is halted / hanging after creating db connection. here is my codebase.</p>
  <p><strong>When I am using module specific dababase connection, then it is working fine, but when I am using common database connection it is hanging</strong></p>
  <p><strong>Common DB Module</strong></p>
  <pre><code>'use strict'
  
  const mongoose    = require('mongoose');
  const DBOptions   = require('./DBOption');
  require(&quot;dotenv&quot;).config();
  mongoose.Promise = global.Promise;
  let isConnected;
  
  const connectToDatabase = (MONGODB_URL) =&gt; {
  
    if (isConnected) {
      console.log('using existing database connection');
      return Promise.resolve();
    }
  
    console.log('using new database connection');
    console.log('DBOptions &gt;&gt; '+JSON.stringify(DBOptions));
    
    return mongoose.connect(MONGODB_URL, DBOptions)
          .then(db =&gt; { 
            console.log('db.connections[0].readyState &gt;&gt; '+db.connections[0].readyState);
            isConnected = db.connections[0].readyState;
          });
  };
   
  module.exports = connectToDatabase;
  </code></pre>
  <p><strong>API Controller</strong></p>
  <pre><code>const dbConnection      = require('../DB/connection') // Internal Class
  const DBConnection      = require('as-common-util').connectToDatabase; // Common Class
  
  /**
   * 
   */
  app.get('/usr/alluser', async (req, res) =&gt; {
    try {
      //await dbConnection(process.env.MONGODB_URL) // This is working
      await DBConnection(process.env.MONGODB_URL) // Code is hanging for this
      let allUsers = await UserService.getAllUser()
      console.log(&quot;All Users &gt;&gt; &quot; + allUsers)
      if (allUsers) {
        return res.status(200).send(
          new APIResponse({
            success: true,
            obj: allUsers
          })
        )
      }
    } catch (error) {
      console.log(error)
    }
  })
  
  </code></pre>
  <p>It is hanging at following position</p>
  <pre><code>using new database connection
  DBOptions &gt;&gt;   
  {&quot;useNewUrlParser&quot;:true,&quot;useUnifiedTopology&quot;:true,&quot;useCreateIndex&quot;:true,&quot;useFindAndModify&quot;:false,&quot;autoIndex&quot;:false,&quot;poolSize&quot;:10,&quot;serverSelectionTimeoutMS&quot;:5000,&quot;socketTimeoutMS&quot;:45000,&quot;family&quot;:4}
  db.connections[0].readyState &gt;&gt; 1
  </code></pre>
  <p><strong>I am confused why same code is not working for common module.</strong></p>