Jim
Jim

Reputation: 2322

How to configure mongoDB connection in heroku-deployed app?

An application deployed to heroku which connects to mongoDB will have issues in this connection attempt because IP's that connect to mongoDB have to be whitelisted inside mongo.

MongoDB docs here say:

To grant programmatic access to an organization or project using only the API, create an API key.

API keys have two parts: a Public Key and a Private Key. You can't use an API key to log into Atlas through the user interface.

All API keys belong to the organization, but can be given access to a project.

To create and manage API keys, use the Access Manager.

When you create a new API key, Atlas grants key the following permissions:

This is how i connected in development:

keys.js:

module.exports = {
  mongoURI: `mongodb+srv://user:[email protected]/administrators?retryWrites=true&w=majority`,
  jwtSecret: 'secret'
}

server.js:

const db = require("./config/keys").mongoURI

mongoose
  .connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err))

What i still dont understand is how to connect to mongoDB from a heroku deployed node.js app once you have an api key initialized??

Upvotes: 1

Views: 280

Answers (1)

Hussam
Hussam

Reputation: 1706

Since heroku dyno always has a random IP from a set of ranges there can be 3 possible ways:

  1. Using Heroku published IP ranges published in order to allow access to Heroku Dynos. This is highly not recommended since Heroku may change those ranges which can change.

  2. Use add-ons to provide outbound static IP to your application that you can add in Atlas network access.

  3. Buy Heroku private spaces which is somewhat expansive

Also if you can't afford to go for both of those recommended options you can allow access from anywhere which is also not highly recommended if you are building an application for production.

Hope it would help

Upvotes: 2

Related Questions