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 connectionvar 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 insertres.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 + ‘/’);
mkdir node_modulesnpm install mongoskin
vmc push appname