Connecting to MongoHQ on Node, error
Question
I'm trying to connect an app I have built to a MongoHQ Database.
This is the code:
mongo = require('mongodb')
Server = mongo.Server
Db = mongo.Db
BSON = mongo.BSONPure;
con = null;
server = new Server('staff.mongohq.com', 'THE_PORT', {auto_reconnect: true});
DBCon = new Db('THE_DB', server, {safe: false});
DBCon.authenticate('test_user', 'test_pass', function() {});
DBCon.open(function(err, db) { if(!err) { con = db; } });
I have the database and the user created in MongoHQ. When I connect from the command line, everything works perfectly.
But when I run my app, I get this error:
return this.connectionPool.getAllConnections();
TypeError: Cannot call method 'getAllConnections' of undefined
It fails to connect to the database. But when I connect to my local database without authentication, it works properly.
So what is the error and how should I fix it?
Thanks! :D
Solution
Your authentication call is being sent before the connection has been established. You need to nest the authenticate call within the "open" callback, something like this should work:
mongo = require('mongodb')
Server = mongo.Server
Db = mongo.Db
BSON = mongo.BSONPure;
con = null;
server = new Server('staff.mongohq.com', 'THE_PORT', {auto_reconnect: true});
DBCon = new Db('THE_DB', server, {safe: false});
DBCon.open(function(err, db) {
if(!err) {
db.authenticate('test_user', 'test_pass', function(err){
if(!err) con = db;
}
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow