Using MongoDB on heroku without verifying your account.
Started learning node and have been writing a simple API using express for practice. After configuring some routes I wanted to get the API live and tried heroku for that.
API uses MongoDB via mongoose ORM. On Heroku you can setup a MongoDB database using addons like mongolab etc.
Problem Heroku requires your credit card information for some addons even for sandbox account. Which you don’t want to when using a sandbox account or just learning something just like me.
Solution
The solution in simple words is, set up a mongodb database but not using heroku and use this.
HOW?
As you know all you need to connect to a db is connection string. For mongo you have connection string something like this.
mongodb://<user>:<password>@<hostname>:<port>/<database>
Head over to https://mlab.com/ and register a sandbox account and follow along.
- Register and verify your account.
- Select the sandbox plan.
- Create the database.
- Create a new db user for this database.
- In this page under your database name you will see a connection string mentioned with the name MongoDB URI which looks something like this. Yours will be different.
mongodb://<dbuser>:<dbpassword>@de243578.mlab.com:47178/todoapp - Fill in all the details. here. For the following db details the MongoURI would become
dbuser : gunther
dbpassword: centralperk
mongodb://gunther:centralperk@de243578.mlab.com:47178/todoapp - Now you have connection string ready to use in your code
But, One last step.
Set this connection string to a Heroku environment variable so your code on heroku knows this connection string. cd into your project directory.
heroku config:set MONGOLAB_URI = "mongodb://gunther:centralperk@de243578.mlab.com:47178/todoapp"
and hit enter and you done to use this in your code. This value you set you can access this using process.env.MONGOLAB_URI
In my instance I am using mongoose to connect to MongoDB so this is how my code looks like for the connection.
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://127.0.0.1:27017/TodoApp');
With this in place, you have a mongodb on your heroku application !