简体   繁体   English

连接到Node上的MongoHQ,错误

[英]Connecting to MongoHQ on Node, error

I'm trying to connect an app I have built to a MongoHQ Database. 我正在尝试将我构建的应用程序连接到MongoHQ数据库。

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. 我有在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 :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;
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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