Introduction to Cloud9 & MongoDB

If you are not familiar, Cloud9 is a fully online editor plus PaaS (platform as a service) for building node.js projects. There’s no need to download or install anything (locally… though you can install a browser plugin to make development easier). It’s so cloudtastic, it’s veritably vaporous. The only problem is, it has no database backend. I wanted to use Mongo, so here’s another situation where DBaaS (database as a service) really shines.

Before we begin, you’ll need a Cloud9 account and a MongoHQ account. The small versions of both are free, so just go get one. Done?

First thing to do in the Cloud9 console is install MongoSkin. Just type in the console:

npm install mongoskin  

If you want to use something else, like Mongoose, or the raw MongoDB driver, that’s OK, too. I like MongoSkin because it straddles that fine line between driver power, without being an overbearing object mapper.

Next, create a file. I called mine “datefinder.js”. Then click then arrow beside run to configure your server, adding the file name to the filepath field. Now, whenever you click Run, your file will be executed as a node.js project.

To continue, we need to get the connection URL from your MongoHQ database. Log into MongoHQ, select your database, and click the Database Info tab. Put in your username and password into the URL (mine is ”imbringing” and ”sexyback”, respectively). Use this url to build your connection object in your Cloud9 project.

var conn = mongo.db('imbringing:sexyback@rose.mongohq.com:10029/blackbook');  

Now we just need to get our collection, and perform an action on it, like find or insert.

conn.collection('ladies').find({area_codes:503})  

Then it’s a simple matter of attaching a callback to whatever form we want the data.

conn.collection('ladies').find({area_codes:503}).toArray(function(err, items){  

Just to make this a little extra delicious, let’s wrap our database call in an http server, and output our response to the client.

var http = require('http'),  
   mongo = require('mongoskin');

http.createServer(function (req, res) {

  var conn = mongo.db('imbringing:sexyback@rose.mongohq.com:10029/blackbook');
  conn.collection('ladies').find({area_codes:503}).toArray(function(err, items){
    if(err) throw err;

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(items));
  });

}).listen(process.env.C9_PORT, "0.0.0.0");
console.log('Server running...');  

That’s all, folks. MongoHQ + Cloud9 = Bliss + Powerful + Free. Yes, that’s three things… that’s synergy.