Deploying apps using MongoDB to Heroku
To deploy your application that is using MongoDB to Heroku you need a MongoDB server running in the cloud. mLab provides hosted MongoDB servers in the cloud.
Use mLab to deploy your application:
- Register on mLab
- Create a new MongoDB deployment using a free Sandbox instance
- Click on the MongoDB deployment you created and create a username and password for your database deployment.
In your application:
- Make you MongoDB connection URL configurable using an environment variable
Use code like this:
const mongoURL = process.env.MONGO_DB_URL || "'mongodb://localhost/test'";
mongoose.connect(mongoURL);
In Heroku:
Add an Config Variable under the Settings tab. Enter a key and value.
The key should be, MONGO_DB_URL the value should be something like, mongodb://<mongo_username>:<mongo_password>@yourinstance.mlab.com:62059/db-name
After setting this up your application on Heroku should be up and running using MongoDB. You might need to restart your application in Heroku.