简体   繁体   中英

Connecting to MongoHQ on Node, error

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

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;
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM