Steven Edouard

Developer Advocate. Tech Enthusiast. Life Enthusiast.


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>





{"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> <itemId returned from step 15>



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:


Happy Coding!




Using JSON Configuration files for Azure Mobile Services

If you log into your Azure Mobile Services (AMS) portal, you'll notice that you can now deploy your service via Git. This is an awesome feature that makes life way easier. Scott Guthrie has a really good post on it.


I'm used to building full fledged cloud services (with worker roles, web roles etc). With AMS, you get a bit more platform, and not as much knowledge about the infrastructure compared to other PaaS services like web and worker roles. Which is great but really became a pain when I was trying to use configuration files with my mobile services.

Most people like to keep their settings like access keys, connection strings, account settings etc. in one place. And if you're using Node.js for your mobile services (which I'm really becoming a fan of by the way!) you probably want to have some sort of JSON configuration like this:



Personally I like to use nconf to read my configuration file because its really straight forward. The problem is that azure mobile doesn't provide you with very much information with the environment in which your code is running. That's the point of PaaS... isn't it? :-)

Well anyways if you follow the how-to on the nconf npm page you'll run into a problem. Say that you have a custom api like so:

nconf.argv().env().file({ file: '../shared/config.jsn' });
exports.get = function(request, response) {
    // Use "request.service" to access features of your mobile service, e.g.:
    //   var tables = request.service.tables;
    //   var push = request.service.push;
    var accountName = nconf.get('Storage.AccountName');
    console.log('Connecting to blob service account: ' + accountName);


And that you place your config.jsn in your shared folder under <ProjectRoot>/shared/config.jsn you'll be surprised when you look at your log output:

'Connecting to blob service account: undefined'


So what's going on here? It turns out (after a good amount of testing what worked and what did not) that there's something funky going on with the current executing directory. So instead, if you want to get to the configuration file, use __dirname + '/path/to/configfile.jsn'

Note: As unintuitive as it sounds, don't name your config file with the extension '.json' or azure will confuse that with a route configuration. It will break your apis with mysterious 500 errors.

So the working verison of the example above (assuming you placed your configuration file in the shared folder) is:

nconf.argv().env().file({ file: __dirname + '/../shared/config.jsn' });
exports.get = function(request, response) {
    // Use "request.service" to access features of your mobile service, e.g.:
    //   var tables = request.service.tables;
    //   var push = request.service.push;
    var accountName = nconf.get('Storage.AccountName');
    console.log('Connecting to blob service account: ' + accountName);


After this everything seems to be in working just fine. So to sum it up, to use json config files in your azure mobile service:

1) DON'T name the config file with the extension .json (it'll make you get unexplained 500's on calls to your apis')
2) DO use the __dirname special node.js property to make the file path absolute at run-time.

Hope this saves you some time!

'Til next time!