Last active
August 29, 2015 14:01
-
-
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
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 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