I'm trying to create a mongoClient connection pool module to use in my project. The problem is the first time I load the page and the mongoFactory is called, it seems that my mongoConnection is not established yet. Every other time after that I load the page it works just fine. Not sure what i'm missing here..
Here's my mongoFactory.js
/**
* Creates and manages the Mongo connection pool
*
* @type {exports}
*/
var constants = require('../js/constants.js');
var Q = require('q');
var MongoClient = require('mongodb').MongoClient;
var db = null;
var getDb = function() {
console.log('db = '+db);
// If the connection pool has not been created or has been closed, create it, else return an existing connection
if (db === null) {
var def = Q.defer();
// Initialize connection once
MongoClient.connect(constants.mongoUrl, function (err, database) {
if (err) {
def.reject(err);
throw err;
}
console.log('inside connection');
db = database;
def.resolve();
});
def.promise.then(function () {
console.log('before returning connection');
return db;
});
} else {
console.log('connection already exists. returning');
return db;
}
}
module.exports.getDb = getDb;
Here's my file that i'm calling the mongoFactory
var mongoFactory = require('../../lib/mongoFactory');
module.exports = function() {
return {
find: function find(callback) {
var db = mongoFactory.getDb();
var cases = db.collection('mycollection'); // <-- First time i load the page, errors b/c db is undefined. Every other time after that it works just fine. ERROR: TypeError: Uncaught error: Cannot call method 'collection' of undefined
...