0

Hey guys so I'm pretty new to creating modules, I'm having a bit of trouble accessing my mongodb connection pool from my main application.

Here's the module:

// mongo-pool.js
// -------------

var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'connection_url';

var mongoPool = {
    start: function() {
        MongoClient.connect(url, function(err, db) {
            assert.equal(null, err);
            console.log("Successfully connected to mongo");

            // Make the db object accessible here?

        });
    }

}

module.exports = mongoPool;

When I require mongo-pool.js and call mongoPool.start() It says it successfully connected to mongo, although the db object is not accessible to make queries. Here is the main js file:

var mongoPool = require('./mongo-pool.js');
var pool = mongoPool.start();


var collection = pool.db.collection('accounts');
collection.update(
    { _id: 'DiyNaiis' },
    { $push: { children: 'JULIAN' } }
)

The variable pool is undefined. I can't seem to figure out why, I've tried return db in the module, didn't seem to work.

Any help is appreciated, thank you!

Julian Guterman
  • 177
  • 1
  • 6

1 Answers1

0

A buddy of mine helped me figure out what the problem was, here's the solution incase anyone runs into it.

I updated my mongo-pool.js module and assigned the db property to itself:

var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'my_database_url';

var mongoPool = {
start: function() {
    MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);

        var self = this;
        self.db = db;
        // THESE ASSIGNMENTS

        console.log("Successfully connected to mongo");

        // Make the db object accessible here?

    });
}

}

module.exports = mongoPool;

Then in my main.js file:

var mongoPool = require('./mongo-pool.js');
// Include My mongo global module

new mongoPool.start();
// Initialize the new MongoDB object globally

setTimeout(function() {
    console.log(db);
}, 3000);
// Set a 3 second timeout before testing the db object...
// It will return undefined if it's called before the mongo connection is made

Now the db object is globally available from a module.

Julian Guterman
  • 177
  • 1
  • 6