mLab: Development with a Database-as-a-Service

With the growth of cloud-based services, developing in a local environment is requiring less and less configuration of that environment. Installing and configuring database software can be particularly tricky for those just getting started, so why not take advantage of services in the cloud?

If you are developing apps that utilize MongoDB, mlab provides are great service to get you connected to your database quickly, and from anywhere. Most importantly, there is a free tier.

mLab Landing Page

Getting Started

First, sign up for an account and verify your email address. The main dashboard should look something like the image below, and you'll want to click on the option to create a new MongoDB Deployment.

Create a new database

Next, you will be given a choice of three database cloud providers. All three offer free plans, so choose your favorite company and be sure to select the Sandbox plan type.

Choose a plan

After pressing continue, choose the region closest to you. Keep follow the creation wizard and then submit your order. Once the database has been successfully initialized, your user dashboard should look something like the image below.

User dashboard

Creating a Database Admin

Click on the new database instance from the list. In order to connect to the database, we need to create a user with administrative priviledges. On the database detail page, click the Users tab, then click Add database user.

Add a user

Enter the admin's credentials, and leave the read only option unchecked.

Connecting to the Database

With the user created, we can connect to the database from our app. Still on the database detail page, look for the MongoDB URI:

mongodb://<dbuser>:<dbpassword>@ds151662.mlab.com:51662/myfirstdatabase

Copy this link into the file that connects to the database. Using a Node server with Mongoose.js, The code to connect would look like this:

mongoose.connect(
  'mongodb://<dbuser>:<dbpassword>@ds151662.mlab.com:51662/myfirstdatabase', 
  /* if you receive a deprecation warning about the connection, add this option */
  { useMongoClient: true }
);
// replace <dbuser> and <dbpassword> with the credentials of the user you created

That's it! All other database related code will be the same as if you were using a local copy of MongoDB.

Previous Post Next Post