gpt4 book ai didi

node.js - 无法使用我的 heroku 应用程序连接到 mongodb 数据库?

转载 作者:可可西里 更新时间:2023-11-01 10:45:03 24 4
gpt4 key购买 nike

我无法将部署到 Heroku 的 Node.js 应用程序与 MongoDB 数据库连接起来。它在本地主机上运行良好,但在 Heroku 上运行不正常。

在我的日志中,我看到了这个:

MongoNetworkError: failed to connect to server [authproject-shard-00-01-ybey8.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to authproject-shard-00-01-ybey8.mongodb.net:27017 closed]


自定义环境变量.json:

{
"db": "Auth_db"
}

default.json:

{
"db": "mongodb://localhost/user"
}

db.js:

  const db = config.get("db");
mongoose
.connect(db)
.then(() => console.log("connected to mongodb.."))
.catch(err => console.error("could not connect to mongodb", err));
};

最佳答案

您需要在 Heroku 应用程序中配置一个环境变量。

在控制台中运行:

heroku config:set MONGODB_URI='urlOfYourMongoDatabase'

然后像这样升级你的 db.js:

const mongoose = require('mongoose')

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/TodoApp', { useNewUrlParser: true })
.then(connect => console.log('connected to mongodb..'))
.catch(e => console.log('could not connect to mongodb', e))

module.exports = {mongoose}

祝你好运!

关于node.js - 无法使用我的 heroku 应用程序连接到 mongodb 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com