Skip to content

Instantly share code, notes, and snippets.

@toymachiner62
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toymachiner62/75d56de073aa2e3d66bc to your computer and use it in GitHub Desktop.
Save toymachiner62/75d56de073aa2e3d66bc to your computer and use it in GitHub Desktop.
Simple MongoDB connection pool factory.
/**
* 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;
}
}
}
}();
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