I created a post route in my node.js website that allows users to apply for a job. It was working great locally and connecting to mongodb atlas but when I pushed the app to Heroku and try to submit the form for the job application my website times out. I am fairly new at this and do not know what to do. Thanks
Here is my code
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Applicant = require('./models/applicants');
var sendAppliedEmail = require('./mail/index.js');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname + '/js'));
var port = process.env.PORT || 3000;
mongoose.connect('mongodb+srv://klaurtar:************@cluster0-nakj7.mongodb.net/test?retryWrites=true', {useNewUrlParser: true});
app.use(bodyParser.urlencoded({extended: true}));
here is my terminal when i run heroku logs
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
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.
- Go to you Heroku application click on Settings
- Click on Reveal Config Vars
- add a new KEY: MONGODB_URL
- add a new VALUE: YOUR CONNECTION STRING
- 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;
Is your MongoDB running on GCP or Azure? If so, they require an IP Whitelist of 0.0.0.0/0 and then Restart All Dynos on your Heroku browser console (it is located in the top right More dropdown).
These articles were helpful:
https://docs.atlas.mongodb.com/security-whitelist/
.17 on: https://cloud.google.com/community/tutorials/mongodb-atlas-appengineflex-nodejs-app