With regards to deploying mLab, I have done it several times from Heroku. It was a little confusing at first, but makes sense once you get used to it.
First of all, you need your mLab. Create your mLab. You want the free/sandbox tier. Once that is created, you will go to the “Users” section and make a user/password. This is different than your mLab account - this is so you can have different users accessing different things and control what they can access. Click on “Add database user” and add a user. After you do this, above you will see a box with the following information:
To connect using the mongo shell:
mongo ds235778.mlab.com:35778/asdf -u <dbuser> -p <dbpassword>
To connect using a driver via the standard MongoDB URI (what's this?):
(“asdf” was just the name I gave the DB.)
This is the information you will need for heroku.
Go to heroku. I found it easiest to create environment variables to keep these values. In node, you can use the
dotenv package that allows you to save your “secret” information in a file called
.env and then if you include that file in your
.gitignore, no one can see it. This is great for passwords, API keys, etc. It also makes it extremely easy to port to heroku and set all those up as environment variables.
So, in my source files, I have a
.env file where I have something declared like:
This is the same string that mLab gave me except that I have substituted in the user name and pwd, assuming that they are “user123” and “pwd123”. Remember, these are not your mLab account username and password, but for the user you set up for this specific database.
In your application, you have:
const MongoClient = require('mongodb').MongoClient;
Those variables from the
.env file are automatically loaded into the `process.env’ object when you run the code. At this point, you should be able to run your code locally and access the mLab data.
The nice thing is that heroku also has a
process.env object, but we don’t access it with a
.env file (we don’t want that stored in the git) but through “config variables”. Go to your heroku app and select “settings”. Select “Reveal Config Variables”. From there, you simply enter anything you had in your
.env file. For example, I add a line with a key (on the left) of “MONGO_DB” and a value (on the right) of “MONGO_DB=mongodb://user123:firstname.lastname@example.org:35778/asdf”.
I think that’s basically it. Of course, you can skip the environment variables part and just hard code your mLab string straight into your code, but I think that’s bad practice because people can look at your github and get those usernames and passwords. It’s a little extra typing to hide them, but not much.
Hope this helps.