Using CloudFoundry with Node.JS and MongoDB

This isn’t so much a question, just a bit of extra documentation for people. There’s not a lot of clear examples on how to make a simple connection from CloudFoundry to Mongo DB when you’re using NodeJS, so I thought I’d stick up this example using the simple to use MongoDB mongoskin wrapper. The MongoDB native driver for Node is a bit awkward when you’re using authentication, so I skipped to the mongoskin layer, which is almost identical.

In your application directory, you need to a file called app.js containing the following code:

var mongodb = require(‘mongoskin’);
var env = JSON.parse(process.env.VCAP_SERVICES);
var mongo = env[‘mongodb-1.8’][0][‘credentials’];
var mongourl = “mongo://” + mongo.username + “:” + mongo.password + “@” + mongo.hostname + “:” + mongo.port + “/” + mongo.db + “?auto_reconnect=true”;
console.log(mongourl);
var db = new mongodb.db( mongourl ); //This is the connection

var http = require(‘http’)
port = Number(process.env.VCAP_APP_PORT || 3000),
host = process.env.VCAP_APP_HOST || ‘localhost’;

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
var currentdate = new Date();

db.test.insert({ daterecord:  currentdate }, {}); //This is the insert

res.end(‘Welcome to Cloud Foundry!\n’ +
host + ‘:’ + port + ‘\n’ +
require(‘util’).inspect(process.env, false, null) + ‘\n’ + fullresult + ‘\n’);
}).listen(port, host);
console.log(‘Server running at http://’ + host + ‘:’ + port + ‘/’);
You also need a subdirectory called node_modules containing the mongoskin module. Using the latest version (1.0.3 of npm) to do this, run:
mkdir node_modules
npm install mongoskin
then run
vmc push appname
When asked if you want to bind a service, say Yes, then pick MongoDB.
The username, password, etc, are picked up automatically in the app.js file.
All the script actually does is insert a new record each time you visit the page, containing the current date, then dumps out all the environment variables to screen, so you can see where the database details are gathered from.
Hope this helps some people, if you have any problems with the code please leave me a comment on here!