title: Creating a DB service in an MVC Express app
body: <p>I am creating a Node / Express / Mongo app and would like to have an MVC-style file layout with a separate database service.  I'd like my routes (controllers) to be fairly lean and simply call methods from elsewhere when I need to perform CRUD functions.</p>
  
  <p><a href="https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module">This great post</a> had a lot of solid answers.  I'll paste below the the answer from <a href="https://stackoverflow.com/users/4705248/eddiedean">EddieDean</a> that seems to be closest to what I'd like to do.</p>
  
  <p>However, when I'm trying to reference the Users object defined in the <code>mongo.js</code> file in my <code>someFile.js</code> file, it comes back as <strong>undefined.</strong>  I am pretty sure I am missing something obvious and would love to know what that is.</p>
  
  <p>I can get a reference to the DB connection itself and call <code>dbConn.Users.addUser(x)</code> but I cannot directly call <code>Users.addUser(x)</code> as in the <code>someFile.js</code> example below.</p>
  
  <p>This seems minor but I've spent too much time on this to not have an answer.  Call it a knowledge vendetta.</p>
  
  <p>Thanks.</p>
  
  <hr>
  
  <p>mongo.js</p>
  
  <pre><code>const { MongoClient } = require('mongodb');
  const config = require('./config');
  const Users = require('./Users');
  const conf = config.get('mongodb');
  
  class MongoBot {
    constructor() {
      const url = `mongodb://${conf.hosts.join(',')}`;
  
      this.client = new MongoClient(url, conf.opts);
    }
    async init() {
      await this.client.connect();
      console.log('connected');
  
      this.db = this.client.db(conf.db);
      this.Users = new Users(this.db);
    }
  }
  
  module.exports = new MongoBot();
  </code></pre>
  
  <p>Users.js</p>
  
  <pre><code>class User {
    constructor(db) {
      this.collection = db.collection('users');
    }
    async addUser(user) {
      const newUser = await this.collection.insertOne(user);
      return newUser;
    }
  }
  module.exports = User;
  </code></pre>
  
  <p>app.js</p>
  
  <pre><code>const mongo = require('./mongo');
  
  async function start() {
    // other app startup stuff...
    await mongo.init();
    // other app startup stuff...
  }
  start();
  </code></pre>
  
  <p>someFile.js</p>
  
  <pre><code>const { Users } = require('./mongo');
  
  async function someFunction(userInfo) {
    const user = await Users.addUser(userInfo);
    return user;
  }
  </code></pre>