Connecting to MongoHQ with Node.js MongoDB Native
I’m using MongoHQ for a Node.js app I’m deploying on Heroku and couldn’t find it plainly documented anywhere how to connect to MongoHQ using node-mongodb-native, so enjoy:
/**
* NOTE: whitespace added for readability
*
* EXAMPLE OPTIONS:
* var options = {
* host: 'flame.mongohq.com',
* port: 27087,
* db: 'your_db',
* username: 'your_username',
* password: 'your_password'
* };
*
**/
DataProvider = function(options) {
//store this for later use
var _parent = this;
//connect to the db
this.db = new Db(
options.db,
new Server(
options.host,
options.port,
{auto_reconnect: true},
{}
)
);
//open the db connection and then authenticate
this.db.open(function(err) {
_parent.db.authenticate(
options.username,
options.password,
function(err) {
if (err) {
console.log(err);
}
}
);
});
});