无法通过heroku上的node.js连接到mongolab [英] can't connect to mongolab with node.js on heroku

查看:102
本文介绍了无法通过heroku上的node.js连接到mongolab的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用mongolab在heroku上制作node.js和mongodb时遇到了麻烦。我已阅读其他问题,如如何设置MongoDB数据库在Heroku上使用MongoLab?如何管理Node.js Web应用程序中的MongoDB连接?,但我仍然无法建立连接。在日志中显示[错误:无法连接到...]

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 ...]

我从MONGOLAB_URI进程环境中获取数据库,主机和端口。我有以下代码:

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 ?

推荐答案

核心问题似乎是您尝试使用MongoDB URI作为主机名。

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

以下是如何使用一个URI和 MongoClient

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! */
});

当然,您需要用用户 pass , host port uri 中的code> db 作为您的实际连接参数。如果您使用 Heroku的MongoLab插件,则可以从环境中获取URI这个:

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;

当使用 MongoClient 安全模式是默认,所以这个选项可以省略。要指定 auto_reconnect ,只需将其作为服务器选项传递即可。 $ b

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! */
});

这篇关于无法通过heroku上的node.js连接到mongolab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆