简体   繁体   English

MongoDb Atlas 未连接到 Heroku

[英]MongoDb Atlas not connecting to Heroku

I have whitelisted all IPs 0.0.0.0/0 in MongoDb Atlas.我已将 MongoDb Atlas 中的所有 IP 0.0.0.0/0 列入白名单。

I set the MONGO_URI config var in Heroku (config key is MONGO_URI and value is set correctly).我在 Heroku 中设置了 MONGO_URI 配置变量(配置键是 MONGO_URI 并且值设置正确)。

this is my db.js code这是我的 db.js 代码

if (process.env.NODE_ENV !== 'production') { require('dotenv').config() }
const mongoose = require('mongoose')

const connectDB = async () => {
    const db = process.env.MONGO_URI
    try {
        await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useFindAndModify: false,
            useUnifiedTopology: true
        })

        console.log('MongoDB Connected...')
    } catch (err) {
        console.error(err.message)
        // Exit process with failure
        process.exit(1)
    }
}

module.exports = connectDB

Anyone know the issue here my app otherwise works perfectly it just doesn't connect to the database.任何人都知道这里的问题,否则我的应用程序可以完美运行,只是无法连接到数据库。

By default process.env.NODE_ENV is production on Heroku, so it won't use.env file even if it is under the project folder.默认情况下process.env.NODE_ENV是 Heroku 上的production ,所以它不会使用 .env 文件,即使它在项目文件夹下。

Adding MONGO_URI and your mongodb connection string key value pair in Heroku should do the trick:在 Heroku 中添加MONGO_URIyour mongodb connection string键值对应该可以解决问题:

  1. login Heroku登录 Heroku
  2. select your app select 您的应用程序
  3. click on settings tab单击设置选项卡
  4. find 'Config Vars' section找到“配置变量”部分
  5. click 'Reveal Config Vars'单击“显示配置变量”
  6. add MONGO_URI as KEY and your connection string(no quote) as VALUEMONGO_URI添加为 KEY 并将your connection string(no quote)添加为 VALUE
  7. click on add button点击添加按钮
  8. open your app again再次打开您的应用

Update: I created a demo using your above code and deployed on Heroku following above steps after connecting it to my git repo.更新:我使用您的上述代码创建了一个演示,并在将其连接到我的 git 存储库后按照上述步骤部署在 Heroku 上。 It works fine.它工作正常。

Live demo现场演示

Source code源代码

You can also check the node console by clicking More -> View logs in the Heroku app page(top right).您还可以通过单击 Heroku 应用页面(右上角)中的More -> View logs来检查节点控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM