Unable to connect to mongodb database with my heroku app?

Viewed 5737

I am unable to connect my Node.js app deployed to Heroku with a MongoDB database. It works fine on localhost, but not on Heroku.

In my logs, I see this:

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]


custom-environment-variables.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));
};
3 Answers

You need to configure an environment variable in your Heroku application.

Run in console:

heroku config:set MONGODB_URI='urlOfYourMongoDatabase'

Then upgrade your db.js like this:

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}

Good luck!

Allow heroku ip access in mongodb by setting allow access from anywhere in network acess in mongodb. this works, but not sure how secured is it by allowing access from anywhere.

In 2021, navigate to your app in Heroku. Click on "Settings" menu. Once it opens expand "Config Vars" by clicking on it. Fill KEY and VALUE fields as it as in your .env file. Suppose you have DB_HOST=url/of/your/mongodb in your .env. The KEY will be DB_HOST and VALUE will be url/of/your/mongodb. Now click on ADD button. You are good to go.

Related