Mongo Connection
A simple way of creating the MongoDB connection string from an object without having to learn the MongoDB connection string rules.
Installation
Using npm
npm install mongoconnection
Usage
var MongoConnection = require("mongoconnection");
var connection = MongoConnection.toString();
The connection
variable will now return mongodb://localhost:27017/
which you can pass straight into the MongoClient object.
Parameters
The following parameters can be passed in
- auth (object)
- host (string/object/array)
- db (string)
- options (object)
Auth
The auth
object can receive an object with the keys "username" and "password".
var connection = MongoConnection.toString({
auth: {
username: "user",
password: "pass"
}
});
// mongodb://user:pass@localhost:27017/
Host
This is the most complex one. Port is always optional, defaulting to 27017. It can receive in the following formats:
- string. Format is "host:port""
- object. Receives host: "string" and "port: number
- array. Can receive array of string or object in above format
Host as string:
var connection = MongoConnection.toString({
host: "example.com"
});
// mongodb://example.com:27017/
Host and port as string:
var connection = MongoConnection.toString({
host: "example.com:9999"
});
// mongodb://example.com:9999/
Host and port in object
var connection = MongoConnection.toString({
host: {
host: "domain.com",
port: 2799
}
});
// mongodb://domain.com:2799/
Multiple
var connection = MongoConnection.toString({
host: [{
host: "domain.com",
port: 2799
}, {
host: "domain.com",
port: 3030
}]
});
// mongodb://domain.com:2799,domain.com:3030/
DB
This just receives the DB as a string
Options
Receives an object and sends it out as a querystring (uses the Node module underneath)
Full Example
var str = MongoConnection.toString({
auth: {
username: "admin",
password: "pa55w0rd"
},
host: [{
host: "localhost"
}, {
host: "backup.example.com",
port: 40380
}],
db: "mydatabase",
options: {
w: 1,
journal: false
}
});
// mongodb://admin:pa55w0rd@localhost:27017,backup.example.com:40380/mydatabase?w=1&journal=false