[英]MongoHQ Node.js connection URL Conection Failed
I have a working Node.js app setup and running well when using my local development MongoDB with these settings and code: 在将本地开发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);
}
});
But when I try to connect with my MongoHQ URI I am getting a Failed to Connect error. 但是,当我尝试连接MongoHQ URI时,出现连接失败错误。
I am unsure as how to use the URI: mongodb://username:password@linus.mongohq.com:10022/my-db with the above code. 我不确定如何使用上面的代码使用URI:mongodb:// username:password@linus.mongohq.com:10022 / my-db。
Edit: Here is the next part of my code to show how I am using the db variable in case it helps with the problem: 编辑:这是我的代码的下一部分,以显示如何使用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');
}
});
}
});
}
Try this: 尝试这个:
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);
});
});
});
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);
}
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.