无法在heroku上使用node.js连接到mongolab

编程入门 行业动态 更新时间:2024-10-20 13:45:02
本文介绍了无法在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 //taken from process.env.MONGOLAB_URI var host = 'mongodb://heroku_appXXXXXX:{password}@ds037518.mongolab'; 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! */ });

当然,您需要替换user、pass、host、port 和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

本文发布于:2023-10-24 14:30:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   node   heroku   mongolab   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!