Reputation: 423
I am having trouble connecting to my MongoDB database which is being deployed on cloud.mongodb.com
at the moment. My webpage is loading fine, but the second I try to access my MongoDB database, it crashes.
I can connect to it when I am just running my node app on my localhost, but the second I switch over to the Heroku application, it gives me this error:
MongoNetworkError: failed to connect to server [cluster0-shard-00-01.32gri.mongodb.net:27017] on first connect [MongoNetworkTimeoutError: connection timed out
I pasted the actual database connection string inside my code (so not even using environment variables!) but it is still not working. My Procfile
looks like this: web: node app.js
and my package.json looks like this:
{
"name": "mortagewebsite",
"version": "1.0.0",
"description": "Shows details about our customers and how close they are to get a mortgage.",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kdonthi/MortgageHelper.git"
},
"author": "Kaushik Donthi",
"license": "ISC",
"bugs": {
"url": "https://github.com/kdonthi/MortgageHelper/issues"
},
"homepage": "https://github.com/kdonthi/MortgageHelper#readme",
"dependencies": {
"express": "^4.17.1",
"joi": "^17.4.2",
"mongoose": "^5.13.7",
"serve": "^12.0.0",
"winston": "^3.3.3"
},
"devDependencies": {
"jest": "^27.0.6"
},
"engines": {
"node": "16.6.2"
}
}
DB connection code (I have replaced PASSWORD
and DBNAME
with the correct replacements as far as I know):
let db = process.env.db || "mongodb+srv://kaushikdr:[email protected]/DBNAME?retryWrites=true&w=majority"
mongoose.connect(db)
.then(_ => console.log("Connected to database."));
The path it is breaking on looks like this (Person
is the model I am using in Mongoose)
app.get("/people/count", (req, res) => {
let filter = req.body.filter ? req.body.filter : {};
getPeopleCount(res, filter);
})
function getPeopleCount(res, filter) {
Person.countDocuments(filter, (error, documentCount) => {
if (error) {
winston.info(error);
res.status(404).send(error);
}
else {
res.send(documentCount.toString());
}
})
}
Thank you for your help!
Upvotes: 1
Views: 726
Reputation: 153
Analysis: If it works perfect on your localhost system, but doesn't work on your Heroku environment, I would check your MongoDB network security settings.
Why: MongoDB ideally wants you to specify your "allowed IP addresses" so you can limit who can access your database. I'm guessing that when you connected to Mongo for the first time, you added your own IP address for localhost testing.
Unfortunately, Heroku doesn't give your Dyno a dedicated IP address. They rotate the IP and port number every time your app restarts. So you need to allow all IP addresses.
The solution:
Login to MongodDB, navigate to Security -> Network Access -> Add IP address
For my application, I had to add 0.0.0.0/0 to the Mongo IP whitelist AND redeploy my app on Heroku.
Upvotes: 5