Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mongodb - can't connect to mongolab with node.js on heroku

I am having trouble making node.js and mongodb with mongolab work on heroku. I have read other issues like How do I setup MongoDB database on Heroku with MongoLab? and How do I manage MongoDB connections in a Node.js web application? but I still can not set up my connection. In the logs it says [Error: failed to connect to ...]

I have takend the db, host and port from the MONGOLAB_URI process env.I have the following code:

var mongoUri = mongodb://heroku_app17328644:{password}@ds037518.mongolab.com //taken from process.env.MONGOLAB_URI 

var host = 'mongodb://heroku_appXXXXXX:{password}@ds037518.mongolab.com';
var port = '37518';
var database = 'heroku_appXXXXXX';

Provider.db = new Db(database, new Server(host, port, { safe: true }, { auto_reconnect: true }, {}));
Provider.db.open(function(err, db){
console.log(db); //null
if (err) console.log(err);
else console.log('success');
});

What am I doing wrong ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The core issue seems to be that you're trying to use a MongoDB URI as a hostname.

Here's how to connect using a URI and MongoClient:

var mongodb = require('mongodb');
var uri = 'mongodb://user:pass@host:port/db';
mongodb.MongoClient.connect(uri, function (err, db) {
    /* adventure! */
});

Of course you'll want to substitute the user, pass, host, port, and db in the uri for your actual connect parameters. If you're using the MongoLab add-on for Heroku you can get the URI from the environment like this:

var uri = process.env.MONGOLAB_URI;

When using MongoClient safe mode is the default, so that option can be left out. To specify auto_reconnect simply pass it as a server option.

var mongodb = require('mongodb');
var uri = 'mongodb://user:pass@host:port/db';
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, db) {
    /* adventure! */
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...