Last active
August 29, 2015 14:05
-
-
Save toymachiner62/75d56de073aa2e3d66bc to your computer and use it in GitHub Desktop.
Simple MongoDB connection pool factory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 dbPromise = null; | |
module.exports = function() { | |
return { | |
/** | |
* Gets a connection to Mongo from the pool. If the pool has not been instantiated it, | |
* instantiates it and returns a connection. Else it just returns a connection from the pool | |
* | |
* @returns {*} - A promise object that will resolve to a mongo db object | |
*/ | |
getConnection: function getConnection() { | |
// If the connection pool has not been created or has been closed, create it, else return an existing connection | |
if (dbPromise === null) { | |
var def = Q.defer(); | |
// Initialize connection once | |
MongoClient.connect(constants.mongoUrl, function (err, database) { | |
if (err) { | |
def.reject(err); | |
} | |
def.resolve(database); | |
}); | |
return dbPromise = def.promise; | |
} else { | |
return dbPromise; | |
} | |
} | |
} | |
}(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoFactory = require('./path/to/mongoFactory'); | |
mongoFactory.getConnection().then(function(db) { | |
.. do stuff with db inside here | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment