Node.js & Compose

Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGOHQ_URL, like this:

Connection string as environment variable
var MONGOHQ_URL="mongodb://"

This code uses the node-mongodb-native driver, though in production you may want something a little less... nesty. Like all good Node packages, you can get it via NPM.

Install Node driver
npm install mongodb

Connecting with Node.js (Javascript)

Connecting to Compose with Node
// npm install mongodb
var mongodb = require('mongodb')
, MongoClient = mongodb.MongoClient
MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
// operate on the collection named "test"
var collection = db.collection('test')
// remove all records in collection (if any)
console.log('removing documents...')
collection.remove(function(err, result) {
if (err) {
return console.error(err)
console.log('collection cleared!')
// insert two documents
console.log('inserting new documents...')
collection.insert([{name: 'tester'}, {name: 'coder'}], function(err,
docs) {
if (err) {
return console.error(err)
console.log('just inserted ', docs.length, ' new documents!')
collection.find({}).toArray(function(err, docs) {
if (err) {
return console.error(err)
docs.forEach(function(doc) {
console.log('found document: ', doc)

Connecting with Node.js (Coffeescript)

Connecting to Compose with Node in Coffeescript
# npm install mongodb
mongodb = require 'mongodb'
url = require 'url'
log = console.log
connection_uri = url.parse(process.env.MONGOHQ_URL)
db_name = connection_uri.pathname.replace(/^\//, '')
mongodb.Db.connect process.env.MONGOHQ_URL, (error, client)->
throw error if error
client.collectionNames (error, names)->
throw error if error
# output all collection names
log "Collections"
log "==========="
last_collection = null
for col_data in names
col_name ="#{db_name}.", '')
log col_name
last_collection = col_name
collection = new mongodb.Collection(client, last_collection)
log "\nDocuments in #{last_collection}"
documents = collection.find({}, limit : 5)
# output a count of all documents found
documents.count (error, count)->
log " #{count} documents(s) found"
log "===================="
# output the first 5 documents
documents.toArray (error, docs)->
throw error if error
for doc in docs then log doc
# close the connection