mongo-connection-string
Utilities to help with MongoDB connection strings and related tasks.
Parsing Connection Strings
Parse a connection string into ConnectionString
object:
const ConnectionString = ;const connectionString = 'mongodb://user:p@ssw0rd@host1,host2:2700/db?w=majority';
The connection string object has the following fields:
{
protocol: 'mongodb://',
username: 'user',
password: 'p@ssw0rd',
hosts: [{ host: 'host1', port: null }, { host: 'host2', port: 2700 }],
database: 'db',
options: {
w: 'majority'
}
}
You can now write it as a MongoDB compatible URI, or a more human readable string:
connectionString; // Produces:// mongodb://user:p%40ssw0rd/db?readPreference=secondary connectionString; // Produces:// mongodb://user:********/db?readPreference=secondary// (a little bit safer to go into logs/error messages etc)!
Building Connection Strings
The ConnectionString
constructor can also take the fields required to build a
connection string:
const ConnectionString = ; const connectionString = ; // Write out the connection string.console;
Produces:
mongodb://user:pwd@host1/db?readPreference=secondary
Url Encoding
When parsing a connection string, encoded charecters are unencoded:
const parse = ;const connectionString = 'mongodb://%40dmin:P%40ssword%3C%3E%2F@host1,host2:2700/db?w=majority'; // Write out the connection string.console;console;
Produces:
@dmin
P@ssword<>/
Similarly, connection string object usernames and passwords are encoded:
const ConnectionString = ; const connectionString = ; // Write out the connection string.console;
Produces:
mongodb://%40dmin:P%40ssword%3C%3E%2F@localhost
This means you can actually use the library to clean up a non-url encoded connection string. This can be useful to allow connection strings to be input in a more readable way (mongo-monitor does this):
'@dmin:P@ssword<>/@localhost';
Produces:
mongodb://%40dmin:P%40ssword%3C%3E%2F@localhost
Notes
- If no protocol is specifed, the library will assume
mongodb://
should be used. - If there is a
%
symbol in the username or password, the code will try to URI decode it. If this fails, it will assume the username or password is plain text with a%
symbol as part of the password. This means that if your password is actually something likep%40ssword
then this will be URI decoded top@ssword
.