Search code examples
node.jsmongodbheroku

Unable to connect to mongodb database with my heroku app?


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));
};

Solution

  • 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!