我在使用我的本地开发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时,我收到了一个连接失败错误。
我不确定如何使用URI:mongodb://用户名: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');
}
});
}
});
}
答案 0 :(得分: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);
});
});
});
答案 1 :(得分: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);
}
});
}
});