2

当使用具有以下设置和代码的本地开发 MongoDB 时,我有一个有效的 Node.js 应用程序设置并运行良好:

var MongoDB     = require('mongodb').Db;
var Server      = require('mongodb').Server;

var dbPort      = 27017;
var dbHost      = 'localhost';
var dbName      = 'my-db';

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
db.open(function(e, d){
if (e) {
    console.log(e);
}   else{
    console.log('connected to database :: ' + dbName);
}
});

但是当我尝试连接我的 MongoHQ URI 时,我收到了 Failed to Connect 错误。

我不确定如何使用上面的代码使用 URI:mongodb://username:password@linus.mongohq.com:10022/my-db。

编辑: 这是我的代码的下一部分,以显示我如何使用 db 变量,以防它有助于解决问题:

var accounts = db.collection('accounts');

/* login validation methods */

exports.autoLogin = function(user, pass, callback)
{
accounts.findOne({user:user}, function(e, o) {
    if (o){
        o.pass == pass ? callback(o) : callback(null);
    }   else{
        callback(null);
    }
});
}

exports.manualLogin = function(user, pass, callback)
{
accounts.findOne({user:user}, function(e, o) {
    if (o == null){
        callback('user-not-found');
    }   else{
        validatePassword(pass, o.pass, function(err, res) {
            if (res){
                callback(null, o);
            }   else{
                callback('invalid-password');
            }
        });
    }
});
}
4

2 回答 2

0

尝试这个:

var mongodb = require('mongodb');
var url = require('url');

var MONGOHQ_URL = "mongodb://username:password@linus.mongohq.com:10022/my-db";

var connectionUri = url.parse(MONGOHQ_URL);
var dbName = connectionUri.pathname.replace(/^\//, '');

mongodb.Db.connect(MONGOHQ_URL, function(error, client) {
    if (error) throw error;

    console.log('Connected to database :: ' + dbName);

    // Some code - Print collection names
    client.collectionNames(function(error, names){
        if(error) throw error;

        console.log("Collections");
        names.forEach(function(colData){
            var colName = colData.name.replace(dbName + ".", '')
            console.log(colName);
        });                            
    });

});
于 2013-01-25T18:48:30.460 回答
0
var username    = 'username';
var passwd      = 'password';


/* establish the database connection */

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
    db.open(function(e, aa){
    if (e) {
        console.log(e);
    }   else{
           aa.authenticate(username, passwd,function(err2,d){
             if(d){
                 console.log("Database opened");
             }
             else{
                 console.log(err2);
             }
         });

    }
});
于 2013-03-26T16:52:37.047 回答