我在使用 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 和
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
发布评论