title: MongoDB in NodeJS Class Structure
body: <p>Is there a way to use MongoDB in a class structure in NodeJS?</p>
  
  <p>I understand you can do CRUD operations on the DB within the connection method like </p>
  
  <p><code>mongo.connect(url, function(err, client){//do some CRUD operation});</code></p>
  
  <p>but I was wondering if there was a way to open the connection to the DB, have access to it across the class, then close it when you are done working with the class.</p>
  
  <p>For example:</p>
  
  <pre><code>class MyClass {
      constructor(databaseURL) {
        this.url = databaseURL;
      }
  
      async init() {
        //make connection to database
      }
  
      async complete_TaskA_onDB() {
        //...
      }
  
      async complete_TaskB_onDB() {
        //...
      }
  
      async close_connection() {
        //close connection to database
      }
  }
  </code></pre>
  
  <p>Edit:</p>
  
  <p>I just came across more information in the <a href="https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html#open" rel="nofollow noreferrer">Node.JS Mongo docs</a>. Maybe something along the lines of this would work?</p>
  
  <pre><code>//constructor()
  this.db = new MongoClient(new Server(dbHost, dbPort));
  
  //init()
  this.db.open();
  
  //taskA()
  this.db.collection(...).update(...);
  
  //close_connection()
  this.db.close();
  </code></pre>