Introduction to Cloud9 and MongoDB


A while ago Mon­goHQ wrote a great article as an introduction to use MongoDB as a service on Cloud9. In the meanwhile we’ve improved our basic MongoDB on Cloud9 IDE support, but we wanted to repost their solution below to show again how easy it is to use MongoDB all in the cloud!

Before we begin, you’ll need a Mon­goHQ account. In this example we’ll use node.js for all code, and we’re assuming you’ve already created your (node.js) workspace.

Install MongoSkin

First thing to do in the Cloud9 Terminal is install Mon­goSkin. Just type in the Terminal:

$ npm install mongoskin

If you want to use some­thing else, like Mon­goose, or the raw Mon­goDB dri­ver, that’s OK, too. I like Mon­goSkin because it strad­dles that fine line between dri­ver power, with­out being an over­bear­ing object mapper.

Setup MongoDB connection

We now need to get the con­nec­tion URL from your Mon­goHQ data­base. Log into Mon­goHQ, select your data­base, and click the Data­base Info tab. Put in your user­name and pass­word into the URL. Use this url to build your con­nec­tion object in your Cloud9 project.

var conn = mongo.db('ivar:test@db.mongohq.com:10029/phonebook', {w: -1});

Now we just need to get our col­lec­tion, and per­form an action on it, like find or insert.

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

Then it’s a sim­ple mat­ter of attach­ing a call­back to what­ever form we want the data.

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

Just to make this a lit­tle extra deli­cious, let’s wrap our data­base call in an http server, and out­put our response to the client.

var http = require('http'), mongo = require('mongoskin'); http.createServer(function (req, res) { var conn = mongo.db('ivar:test@db.mongohq.com:10029/phonebook', {w: -1}); conn.collection('businesses').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.PORT, process.env.IP); console.log('Server running...');

And that’s all there is to get a MongoDB running with Cloud9 and Mon­goHQ!

Ivar Pruijn

Read more posts by Ivar Pruijn.