Skip to content

Instantly share code, notes, and snippets.

@joewagner
Last active August 29, 2015 14:01
Show Gist options
  • Save joewagner/611c31b49dbe17d49168 to your computer and use it in GitHub Desktop.
Save joewagner/611c31b49dbe17d49168 to your computer and use it in GitHub Desktop.
Simple class that may be used to create a pool of mongoose connections with unique MongoURIs
var mongoose = require('mongoose');
var UserSchema = require(__dirname + '/user-schema');
var DatabasePool = function () {
this.dbs = {};
};
// gets a connection to a specific mongo uri string, or
// creates it if it doesn't exist, or isn't connected
// Then attaches "User" Model to the connection
DatabasePool.prototype.getDb = function (uri) {
if (!uri) { return throw new Error('must supply uri!'); }
if (this.dbs[uri] && (this.dbs[uri].readyState === 1 || this.dbs[uri].readyState === 2)) {
return this.dbs[uri];
}
this.dbs[uri] = mongoose.createConnection(uri/*, get options from config */);
this.dbs[uri].model('User', UserSchema);
return this.dbs[uri];
};
module.exports = new DatabasePool();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment