Question

I've encountered a bizarre error trying to connect to a MongoHQ MongoDB on Heroku using NodeJS. It worked before and now it has stopped to work. I can connect to database on my local machine, so I guess that MongoHQ is working just fine. On Heroku, the following minimal example throws "Error: failed to connect to [mongodb://xyz.mongohq.com]". Any idea what's wrong?

var Fiber = require('fibers');
var MongoSync = require("mongo-sync");

Fiber(function() {
  try {
    var server = new MongoSync.Server("mongodb://xyz.mongohq.com:12345");
    var db = server.db("app12345678");
    db.auth("heroku", "password");
    var collection = db.getCollection("my_collection");
    console.log(collection.count());
  } catch (e) {
    console.log(e);
  }
  process.exit(0);
}).run();
Was it helpful?

Solution

Try specifying the database name and auth credentials all in the connection string.

mongodb://heroku:password@xyz.mongohq.com:12345/app12345678

You could also try connecting using MongoClient and connect as outlined in the driver readme doc.

 var MongoClient = require('mongodb').MongoClient,
     format = require('util').format;    

  MongoClient.connect(' mongodb://heroku:password@xyz.mongohq.com:12345/app12345678', function(err, db) {
    if(err) throw err;

    var collection = db.collection('my_collection');
    collection.insert({a:2}, function(err, docs) {

      collection.count(function(err, count) {
        console.log(format("count = %s", count));
      });
    });
  });

If that still doesn't work double check everything--recreate the user you want to connect with and then copy the connection string from MongoHQ's admin page replacing the username and password you just created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top