Skip to content

Instantly share code, notes, and snippets.

@OscarGodson
Created September 11, 2011 04:25
Show Gist options
  • Save OscarGodson/1209163 to your computer and use it in GitHub Desktop.
Save OscarGodson/1209163 to your computer and use it in GitHub Desktop.
How to connect to MongoHQ with Node + node-mongodb-native
/**
* To get all the info to login, sign into your MongoHQ account, go to the db you want,
* click the "Database Info" tab, then look for the line that looks like:
* -------------------------------------------------------------
* mongodb://<user>:<password>@staff.mongohq.com:10056/node-test
* ---------| |-| |------------------| |-| |
* USER PASSWORD PORT DB NAME
*
* ALSO, for testing, you should manually add a document and collection into MongoHQ
* from their "Add a Collection" > "Add a Document" links, then below we'll log it.
*/
//If you haven't already, install the mongodb package w/ npm install mongodb
var mongodb = require('mongodb');
var db;
//The 10056 is the port!
db = new mongodb.Db('example-db', new mongodb.Server('staff.mongohq.com', 10056, {auto_reconnect:true}), {});
db.open(function(err, p_client) {
//Notice the USERNAME and PASSWORD!
db.authenticate('USERNAME', 'PASSWORD', function(err) {
//Change error handler when going into production
if (err) console.log(err);
var collection = new mongodb.Collection(db, 'test_collection');
collection.find({}, {limit:10}).toArray(function(err, docs) {
//In an array, this will log all your documents you added before we tested this
console.dir(docs);
});
});
});
@wesley-pipes
Copy link

How do you reuse the connection without doing an open/authenticate all the time? (I think that there is something fundamental that I do not understand about nodejs...)

@OscarGodson
Copy link
Author

Callbacks :) which isn't as much as nodejs as it is just JS.

You need to keep your application code that needs to get data from the DB inside the db.open(). To break up your code you can do something like:

var client = new Db('test', new Server("127.0.0.1", 27017, {})),
    test = function (err, collection) {
      collection.insert({a:2}, function(err, docs) {

        collection.count(function(err, count) {
          test.assertEquals(1, count);
        });

        // Locate all the entries using find
        collection.find().toArray(function(err, results) {
          test.assertEquals(1, results.length);
          test.assertTrue(results[0].a === 2);

          // Let's close the db
          client.close();
        });
      });
    };

client.open(function(err, p_client) {
  client.collection('test_insert', test);
});

Also, you can most likely have as many db.open()s as you want so you could do more of those.

@OscarGodson
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment