Reputation: 1119
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));
};
Upvotes: 4
Views: 6834
Reputation: 1
"For some reason using the MongoDB connection string from Driver Node.js version 3.0 or later without the '&w=majority' at the end of it leads to a successful deployment. Again, I'm not sure if this is safe or optimal, but, it's working."
Upvotes: 0
Reputation: 29
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.
Upvotes: 0
Reputation: 11
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.
Upvotes: 1
Reputation: 64
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!
Upvotes: 4