Steven Edouard

Developer Advocate. Tech Enthusiast. Life Enthusiast.

NAVIGATION - SEARCH

Azure Mobile & MongoDB? : It's like Peanut Butter & Jelly!

Azure Mobile Services Git Deploy is a new feature of Mobile Services where you can start writing your scripts in the text editor of your choice and deploy by pushing your local repo to Azure.

 

Although this is cool, the really cool thing about this is that unlike before you can add ANY Node.js npm package to your repo. And you know what's really, really, cool? You can use MongoDB as an alternate to Azure Mobile SQL tables!

 

 

So let's get started:

 

1) Sign into your Azure Portal add a new mobile service:

 

 

2) Although we'll be using Mongo, every Mobile Service has an associated SQL database. So just use an existing one or create a new one for free.

 

 

3) After your mobile service is done being created, head over to the API tab. We need to make a custom API for clients to talk to our MongoDB:

 

 

Let's call this API 'todoitem'. For the purpose of this demo, we'll use 'Anybody with the Application Key' security permission. For actual mobile clients I would recommend using 'Only Authenticated Users' to keep your database secure.

 

     We will implement the GET and POST API's

 

 

4) Before mucking with our scripts, lets setup source control so we can get the right stuff needed to connect to Mongo. Head back to the Mobile Service Dashboard:

    

 

 

    Notice the 'Setup source control' on the dashboard. Go ahead and click it.

5) The Portal will automagically take you to the Configure tab, but we gotta set up our source control credentials. Azure generates a default login but I found it to be confusing as to what it actually is.

    Go back to the Dashboard tab Click 'Reset your source control credentials'. Enter a user name and password for your Git account. (Note, you can't use your Micrsofot Account credentials)

 

 

 

 

6) Hop back to your Configure tab and grab the Git URL:

 

 

7) Now to clone the repo! Use your favorite git client and do the following commands in your shell:

 

>git clone <your git repo link>
>Username for '<your git repo link>': <your git username from step 5>
>Password for '<your git repo link>': <your git password from step 5>


8) Navigate to <your service name>/service folder in your local repo. You should see a folder layout as follows:

 

As you can see, azure setup a nicely organized repo for you with your new 'todoitem' api, and a JSON config file for it.

For this demo, we'll use the mongoose Node.js driver. Install Mongoose by navigating to <your service name>/service and running the following command:

>npm install mongoose


If all goes well, your output should end with the package installation similar to this:

 

 

9) As of writing this post, you can't run azure mobile services locally on the emulator, so adding the npm package actually doesn't really do much but mirror what your setup looks like in the cloud. The important thing to do here is open package.json. Ensure that you add mongoose as one of your dependencies:

 

(I found that npm didn't do this automatically in my azure repo)

 

10) Now that we've got our database driver, how the exactly do we get our Mongo database? Luckily to make things easy we have Azure add-ons where we can find MongoLab. (Obviously you don't have to use MongoLab's MongDB, but for this demo that’s what I'll use)

To add MongoLab jump back to your portal, click the plus on the bottom left and select 'Store':

 

 

Pick a sandbox account (which is free) and give it a name. (Make sure to use the same region as your mobile service for best performance!):

 

 

Complete your 'Purchase' and you'll see that you have a MongoLab mongodb in your Add-on's section:

 

 

11) Select Manage which will open up your MongoLab Portal. Select 'Add Collection':

 

 

Call it todoitems:

 

 

Great! Now we've got a place to stash our todoitems for our app!

12) Head back to the portal on and copy the connection string from your Add-on's page by clicking 'Connection info':

 

 

13) Jump over to your Mobile service Configure page, and scroll toward the bottom to app settings. This is a place we can privately put sensitive info like the connection string we copied from MongoLab without placing it directly in our code. Add the setting 'MongoConnectionString' to your app settings and copy the connection string from the previous step as the value.

 

 

 

 

This makes it easy to share your code on github or with other collaborators. Also, if you prefer to use a configuration file, check out my post on using JSON config files instead.

 

14) Now, let's write the POST /api/todoitem API. Go to the API you created in Step 3 and insert the following:

 

 

The scope of this post isn't to necessarily show you how to use mongoose, but do note that you should not compile your mongoose model within the api handler but in the global scope so that it is only compiled once. The model defined by todoItemSchema will associate Todo items and Users. We use the process.env object to get to the connection string we placed in Step 13 to open the connection to mongo and place the JSON object directly in the database. I should caution that it may be a good idea to validate the JSON you recieive for defensive purposes.

 

After your done writing the API implementation go ahead and commit to your repo:

>git commit .
>git push origin master



Now here's the cool part! This will trigger the installation of the npm packages in the remote repo and the deployment to the mobile service. You should see your git console output the installation of mongoose and its dependencies and that the deployment was successful:

 

 

15) Now let's test our POST api! I'll use the Advanced Rest Client chrome extension since its super handy in debugging REST API's. You can do the following request:

POST https://<yourservicename>.azure-mobile.net/todoitem

HEADERS:

X-ZUMO-APPLICATION : <YOUR APPLICATION KEY>

BODY:

 

{"category":"MustDos", "description":"Make more apps!", "user": { "id":"Facebook:2432423", "name": "Steven Edouard" }}

 

Success! The API returned the mongo-generated id of the created object. We've written to our MongoDB from our Azure mobile app! Now, can we get the Mongo object back and party on that?

 

16) Get back to your text editor and add the implementation for the GET api:

 

 

 

 This script returns us the TodoItem whose id matched the itemId url query argument.

 Let's test it out! Do the following call:

 GET https://<yourservicename>.azure-mobile.net/todoitem?itemId= <itemId returned from step 15>

 HEADERS: X-ZUMO-APPLICATION: <YOUR APP KEY>

 

Huzzah! We got our mongo object back!

 

Now you can successfully integrate with mongo in our clients using authenticated apis with MongoDB. Why is this so awesome? As a developer now YOU have more choices in how you can store your data with the ease of using azure mobile services. Depending on your application, scale and costs this gives you a great alternative to Mobile Services SQL Tables.

 

You can find the finished code for this service at: https://github.com/sedouard/AzureMongo

 

Happy Coding!