Skip to content

Commit

Permalink
Mongodb connection establishment update
Browse files Browse the repository at this point in the history
Merge in pull request from original repo, cvallance#105
Changed mongodb connection establishment to support newer driver and database versions of mongodb. The current authentication method (Db.authenticate) is deprecated (see log files). The new way to establish a connection is to use the MongoClient.

I create different connection strings, depending on whether a username is set or not. The way it is implemented only allows authentication against the selected database (i.e. no auth agains admin database when connecting to different db).

It should be tested whether the "encodeURIComponent" calls on the passwords are sufficient to prevent the connection uri from breaking on special character input.
  • Loading branch information
Dave Barnum committed May 14, 2020
1 parent 674e15b commit 205866d
Showing 1 changed file with 10 additions and 18 deletions.
28 changes: 10 additions & 18 deletions src/lib/mongo.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var Db = require('mongodb').Db;
var MongoClient = require('mongodb').MongoClient;
var MongoServer = require('mongodb').Server;
var async = require('async');
var config = require('./config');
Expand Down Expand Up @@ -27,25 +27,17 @@ var getDb = function(host, done) {
}
}

var mongoDb = new Db(config.database, new MongoServer(host, config.mongoPort, mongoOptions));

mongoDb.open(function (err, db) {
var connectionURI;
if (config.username) {
connectionURI = `mongodb://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${host}:${config.mongoPort}/${config.database}`;
} else {
connectionURI = `mongodb://${host}:${config.mongoPort}/${config.database}`;
}
MongoClient.connect(connectionURI, mongoOptions, function(err, db) {
if (err) {
return done(err);
}

if(config.username) {
mongoDb.authenticate(config.username, config.password, function(err, result) {
if (err) {
return done(err);
}

return done(null, db);
});
} else {
return done(null, db);
}

return done(null, db);
});
};

Expand Down Expand Up @@ -214,4 +206,4 @@ module.exports = {
initReplSet: initReplSet,
addNewReplSetMembers: addNewReplSetMembers,
isInReplSet: isInReplSet
};
};

0 comments on commit 205866d

Please sign in to comment.