Adds replica-set support to the mongodb native driver.

Adds replica set support through .rs property for replica set name and
accepts similar url for replica set definition to mongoose.js driver.
This commit is contained in:
Timothy Marks 2012-08-15 00:23:23 +10:00
parent eaa2f026b0
commit 59ba68494d
1 changed files with 50 additions and 17 deletions

View File

@ -11,19 +11,43 @@ exports.initialize = function initializeSchema(schema, callback) {
var s = schema.settings;
if (schema.settings.url) {
var url = require('url').parse(schema.settings.url);
s.host = url.hostname;
s.port = url.port;
s.database = url.pathname.replace(/^\//, '');
s.username = url.auth && url.auth.split(':')[0];
s.password = url.auth && url.auth.split(':')[1];
if (schema.settings.rs) {
s.rs = schema.settings.rs;
if (schema.settings.url) {
var uris = schema.settings.url.split(',');
s.hosts = []
s.ports = []
uris.forEach(function(uri) {
var url = require('url').parse(uri);
s.hosts.push(url.hostname || 'localhost');
s.ports.push(parseInt(url.port || '27017', 10));
if (!s.database) s.database = url.pathname.replace(/^\//, '');
if (!s.username) s.username = url.auth && url.auth.split(':')[0];
if (!s.password) s.password = url.auth && url.auth.split(':')[1];
});
}
s.database = s.database || 'test';
} else {
if (schema.settings.url) {
var url = require('url').parse(schema.settings.url);
s.host = url.hostname;
s.port = url.port;
s.database = url.pathname.replace(/^\//, '');
s.username = url.auth && url.auth.split(':')[0];
s.password = url.auth && url.auth.split(':')[1];
}
s.host = s.host || 'localhost';
s.port = parseInt(s.port || '27017', 10);
s.database = s.database || 'test';
}
s.host = s.host || 'localhost';
s.port = parseInt(s.port || '27017', 10);
s.database = s.database || 'test';
schema.adapter = new MongoDB(s, schema, callback);
};
@ -31,10 +55,20 @@ function MongoDB(s, schema, callback) {
this._models = {};
this.collections = {};
var server = new mongodb.Server(s.host, s.port, {});
var server;
if (s.rs) {
set = [];
for(i=0, n=s.hosts.length; i<n; i++) {
set.push(new mongodb.Server(s.hosts[i], s.ports[i], {auto_reconnect: true}));
}
server = new mongodb.ReplSetServers(set, {rs_name:s.rs});
} else {
server = new mongodb.Server(s.host, s.port, {});
}
new mongodb.Db(s.database, server, {}).open(function (err, client) {
if (err) throw err;
if (s.username && s.password) {
t = this;
client.authenticate(s.username, s.password, function(err, result) {
@ -43,7 +77,7 @@ function MongoDB(s, schema, callback) {
schema.client = client;
callback();
});
} else {
this.client = client;
schema.client = client;
@ -197,5 +231,4 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, cb) {
MongoDB.prototype.disconnect = function () {
this.client.close();
};
};