无法在heroku上使用node.js连接到mongolab [英] can't connect to mongolab with node.js on heroku

查看:21
本文介绍了无法在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');
});

我做错了什么?

推荐答案

核心问题似乎是您试图使用 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! */
});

当然,您需要替换userpasshostport 和<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,只需将其作为服务器选项传递即可.

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天全站免登陆