Mongodb atlas + node.js working locally but stop when pushed to Heroku Mongodb atlas + node.js working locally but stop when pushed to Heroku heroku heroku

Mongodb atlas + node.js working locally but stop when pushed to Heroku


I see that MongoNetworkError is occurring, and if the things are working fine at local but not at Heroku, then IP whitelisting might be the issue. IP need to be whitelisted at MongoDB Atlas before we go for making any connection. In case you don't know the IP (heroku), you can put it as 0.0.0.0/0

IP whiltelisting at MongoDB Atlas (under security tab)

I faced similar issue in past and this worked for me.


I faced the same problem when i tried to move from mlab to Atlas MangoDb. So the solution I found was to add config vars in your Heroku application.

  1. Go to you Heroku application click on Settings
  2. Click on Reveal Config Vars
  3. add a new KEY: MONGODB_URL
  4. add a new VALUE: YOUR CONNECTION STRING
  5. refresh your Heruko application and you are good to go.

PS: Make sure your dbconnection is working. In case of questions i gonna left my connection to compare:

  mongoCFG = {    useNewUrlParser: true,    ssl: true,    replicaSet: '<clusterName>-shard-0',    authSource: 'admin',    retryWrites: true,    useUnifiedTopology: true,  }console.log('Attempting to connect to mongoose');mongoose.connect(config.mongoURL, mongoCFG)  .then(() => {    console.log("Connected to Mongo database!");  })  .catch(err => {    console.error("App starting error:", err.stack);  });```


I whitelisted my IP with mongodb atlas and updated my code to save the uri as a variable and it now works in Heroku production. Here is my code that ended up working.

var uri = "mongodb+srv://klaurtar:************@cluster0-nakj7.mongodb.net/test?retryWrites=true";mongoose.connect(uri, {useNewUrlParser: true});var db = mongoose.connection;