Node.js and MongoLab on Windows Azure

(This tutorial was originally published on the Windows Azure documentation portal in January 2013)

Greetings, adventurers! Welcome to MongoDB-as-a-Service. Are you looking to create a Node.js Application on Windows Azure with MongoDB using the MongoLab Azure Store add-on?

In this tutorial you will:

  1. Provision the database - The Windows Azure Store MongoLab add-on will provide you with a MongoDB database hosted in the Windows Azure cloud and managed by MongoLab's cloud database platform.
  2. Create the app - It'll be a simple Node.js app for maintaining a list of tasks.
  3. Deploy the app - By tying a few configuration hooks together, we'll make pushing our code a breeze.
  4. Manage the database - Finally, we'll show you MongoLab's web-based database management portal where you can search, visualize, and modify data with ease.

At any time throughout this tutorial, feel free to kick off an email to if you have any questions. To complete this tutorial, you need a Windows Azure account that has the Windows Azure Web Sites feature enabled. You can create a free trial account and enable preview features in just a couple of minutes. For details, see the Create a Windows Azure account and enable preview features tutorial.

In addition, ensure that you have the following installed:

Quick start

If you have some familiarity with the Windows Azure Store, use this section to get a quick start. Otherwise, continue to Provision the database below.

  1. Open the Windows Azure Store.
  2. Click on the MongoLab Add-On.
  3. Click on your MongoLab Add-On in the Add-Ons list and then click Connection Info.
  4. Copy the MONGOLAB_URI to your clipboard.
    This URI contains your database user name and password. Treat it as sensitive information and do not share it.
  5. Add the value to the Connection Strings list in the Configuration menu of your Windows Azure Web application:
  6. For Name, enter MONGOLAB_URI.
  7. For Value, paste the connection string we obtained in the previous section.
  8. Select Custom in the Type drop-down (instead of the default, SQLAzure).
  9. Run npm install mongoose to obtain Mongoose, a MongoDB node driver.
  10. Set up a hook in your code to obtain your MongoLab connection URI from an environment variable and connect:
    var mongoose = require('mongoose');  
    var connectionString = process.env.CUSTOMCONNSTR_MONGOLAB_URI

Note: Windows Azure adds the CUSTOMCONNSTR_ prefix to the originally-declared connection string, which is why the code references CUSTOMCONNSTR_MONGOLAB_URI. instead of MONGOLAB_URI.

Now, on to the full tutorial...


Provision the database

You can subscribe to an Azure-hosted, fully-managed MongoDB database in the Windows Azure Store. To do so, follow these steps:

  1. Log into the Windows Azure Management Portal.
  2. Click New.
  3. Select Store.
  4. Select MongoLab. You can find us in the App Services category, as well as under All.
  5. Click Next.
    The MongoLab store entry displays.
  6. Select your desired Subscription option.
  7. Enter a Name for your database. Your name can only contain alphanumeric characters, dashes, dots, and underscores. MongoLab also requires that this name be unique, so you may be asked to re-submit your request if the name is taken.
  8. Select your desired Region.
    Important: For maximum performance and security, we strongly recommend provisioning your MongoLab add-on and Windows Azure web site in the same region. As of this blog date, the MongoLab add-on is available in the East US and West US regions.
  9. Click Next.
  10. Review your store purchase information and click Purchase to confirm.
  11. The toolbar progress button provides your provisioning status.
    A success message displays when provisioning completes.

Congratulations! MongoLab has just provisioned a MongoDB database in the Windows Azure region you selected. You now have access to our management UI and 24/7 support.


Create the app

In this section you will set up your development environment and lay the code for a basic task list web application using Node.js, Express, and MongoDB. Express provides a View Controller framework for node, while Mongoose is a driver for communicating with MongoDB in node.


Generate scaffolding and install modules

  1. At the command-line, create and navigate to the tasklist directory. This will be your project directory.
  2. Enter the following command to install express.
    npm install express -g

    -g indicates global mode, which we use to make the express module available without specifying a directory path. If you receive Error: EPERM, chmod '/usr/local/bin/express', use sudo to run npm at a higher privilege level.

    The output of this command should appear similar to the following:

    express@2.5.9 /usr/local/lib/node_modules/express
    """ mime@1.2.4 
    """ mkdirp@0.3.0 
    """ qs@0.4.2 
    """" connect@1.8.7
  3. To create the scaffolding which will be used for this application, use the express command:

    The output of this command should appear similar to the following:

    create : .
    create : ./package.json
    create : ./app.js
    create : ./public
    create : ./public/javascripts
    create : ./public/images
    create : ./public/stylesheets
    create : ./public/stylesheets/style.css
    create : ./routes
    create : ./routes/index.js
    create : ./views
    create : ./views/layout.jade
    create : ./views/index.jade
    dont forget to install dependencies:
    $ cd . && npm install

    After this command completes, you should have several new directories and files in the tasklist directory.

  4. Enter the following to install the modules described in the package.json file:
    npm install

    The output of this command should appear similar to the following:

    express@2.5.8 ./node_modules/express
    """ mime@1.2.4
    """ qs@0.4.2
    """ mkdirp@0.3.0
    """" connect@1.8.7
    jade@0.26.0 ./node_modules/jade
    """ commander@0.5.2
    """" mkdirp@0.3.0

    The package.json file is one of the files created by the express command. This file contains a list of additional modules that are required for an Express application. Later, when you deploy this application to a Windows Azure Web Site, this file will be used to determine which modules need to be installed on Windows Azure to support your application.

  5. Next, enter the following command to install the Mongoose module locally as well as to save an entry for it to the package.json file:
    npm install mongoose --save

    The output of this command should appear similar to the following:

    mongoose@2.6.5 ./node_modules/mongoose
    """ hooks@0.2.1
    """" mongodb@1.0.2

    You can safely ignore any message about installing the C++ bson parser.

The Code

Now that our environment and scaffolding is ready, we'll extend the basic application created by the express command by adding a task.js file which contains the model for your tasks. You will also modify the existing app.js and create a new tasklist.js controller file to make use of the model.

Create the model

  1. In the tasklist directory, create a new directory named models.
  2. In the models directory, create a new file named task.js. This file will contain the model for the tasks created by your application.
  3. Add the following code to the task.js file:
    var mongoose = require('mongoose')
      , Schema = mongoose.Schema;
    var TaskSchema = new Schema({
        itemName      : String
      , itemCategory  : String
      , itemCompleted : { type: Boolean, default: false }
      , itemDate      : { type: Date, default: }
    module.exports = mongoose.model('TaskModel', TaskSchema)
  4. Save and close the task.js file.

Create the controller

  1. In the tasklist/routes directory, create a new file named tasklist.js and open it in a text editor.
  2. Add the folowing code to tasklist.js. This loads the mongoose module and the task model defined in task.js. The TaskList function is used to create the connection to the MongoDB server based on the connection value, and provides the methods showTasks, addTask, and completeTasks:
    var mongoose = require('mongoose')
      , task = require('../models/task.js');
    module.exports = TaskList;
    function TaskList(connection) {
    TaskList.prototype = {
      showTasks: function(req, res) {
        task.find({itemCompleted: false}, function foundTasks(err, items) {
          res.render('index',{title: 'My ToDo List ', tasks: items})
      addTask: function(req,res) {
        var item = req.body.item;
        newTask = new task();
        newTask.itemName =;
        newTask.itemCategory = item.category; savedTask(err){
          if(err) {
            throw err;
      completeTask: function(req,res) {
        var completedTasks = req.body;
        for(taskId in completedTasks) {
          if(completedTasks[taskId]=='true') {
            var conditions = { _id: taskId };
            var updates = { itemCompleted: completedTasks[taskId] };
            task.update(conditions, updates, function updatedTask(err) {
              if(err) {
                throw err;
  3. Save the tasklist.js file.

Modify the index view

  1. Change directories to the views directory and open the index.jade file in a text editor.
  2. Replace the contents of the index.jade file with the code below. This defines the view for displaying existing tasks, as well as a form for adding new tasks and marking existing ones as completed.
    h1= title
    form(action="/completetask", method="post")
          td Name
          td Category
          td Date
          td Complete
        each task in tasks
            td #{task.itemName}
            td #{task.itemCategory}
            - var day   = task.itemDate.getDate();
            - var month = task.itemDate.getMonth() + 1;
            - var year  = task.itemDate.getFullYear();
            td #{month + "/" + day + "/" + year}
              input(type="checkbox", name="#{task._id}", value="#{!task.itemCompleted}", checked=task.itemCompleted)
      input(type="submit", value="Update tasks")
    form(action="/addtask", method="post")
          td Item Name: 
            input(name="item[name]", type="textbox")
          td Item Category: 
            input(name="item[category]", type="textbox")
      input(type="submit", value="Add item")
  3. Save and close index.jade file.

Replace app.js

  1. In the tasklist directory, open the app.js file in a text editor. This file was created earlier by running the express command.
  2. Replace the contents with the following code. This will initialize TaskList with the connection string for the MongoDB server, add the functions defined in tasklist.js as routes, and start your app server:
    var express = require('express')
        , routes = require('./routes')
        , user = require('./routes/user')
        , http = require('http')
        , path = require('path');
    var TaskList = require('./routes/tasklist');
    var taskList = new TaskList(process.env.CUSTOMCONNSTR_MONGOLAB_URI);
    var app = express();
      app.set('port', process.env.PORT || 3000);
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use(express.static(path.join(__dirname, 'public')));
    app.configure('development', function(){
    app.get('/', taskList.showTasks.bind(taskList));'/addtask', taskList.addTask.bind(taskList));'/completetask', taskList.completeTask.bind(taskList));
    http.createServer(app).listen(app.get('port'), function(){
      console.log("Express server listening on port " + app.get('port'));
  3. Note the following code above:
    var taskList = new TaskList(process.env.CUSTOMCONNSTR_MONGOLAB_URI);

    The TaskList constructor takes a MongoDB connection URI. Here, you access an environment variable that you'll configure later. If you have a local mongo instance running for development purposes, you may want to temporarily set this value to "localhost" instead of process.env.CUSTOMCONNSTR_MONGOLAB_URI.

  4. Save the app.js file.


Deploy the app

Now that the application has been developed, it's time to create a Windows Azure Web Site to host it, configure that web site, and deploy the code. Central to this section is the use of the MongoDB connection string (URI). You're going to configure an environment variable in your web site with this URI to keep the URI separate from your code. You should treat the URI as sensitive information as it contains credentials to connect to your database.

The steps in this section use the Windows Azure command-line tools to create a new Windows Azure Web Site, and then use Git to deploy your application. To perform these steps you must have a Windows Azure subscription.

Install the Windows Azure command-line tool for Mac and Linux

To install the command-line tools, use the following command:

npm install azure-cli -g

If you have already installed the Windows Azure SDK for Node.js from the Windows Azure Developer Center, then the command-line tools should already be installed. For more information, see Windows Azure command-line tool for Mac and Linux.

While the Windows Azure command-line tools were created primarily for Mac and Linux users, they are based on Node.js and should work on any system capable of running Node.

Import publishing settings

Before using the command-line tools with Windows Azure, you must first download a file containing information about your subscription. Perform the following steps to download and import this file.

  1. From the command-line, enter the following command to launch the browser and navigate to the download page. If prompted, log in with the account associated with your subscription.
    azure account download


    The file download should begin automatically; if it does not, you can click the link at the beginning of the page to manually download the file.

  2. After the file download has completed, use the following command to import the settings:
    azure account import <path-to-file>

    Specify the path and file name of the publishing settings file you downloaded in the previous step. Once the command completes, you should see output similar to the following:

    info:   Executing command account import
    info:   Found subscription: subscriptionname
    info:   Setting default subscription to: subscriptionname
    warn:   The '/Users/user1/.azure/publishSettings.xml' file contains sensitive information.
    warn:   Remember to delete it now that it has been imported.
    info:   Account publish settings imported successfully
    info:   account iomport command OK
  3. Once the import has completed, you should delete the publish settings file as it is no longer needed and contains sensitive information regarding your Windows Azure subscription.

Create a new web site and push your code

Creating a web site in Windows Azure is very easy. If this is your first Windows Azure web site, you must use the portal. If you already have at least one, then skip to step 7.

  1. In the Windows Azure portal, click New.
  2. Select Compute > Web Site > Quick Create.
  3. Enter a URL prefix. Choose a name you prefer, but keep in mind this must be unique ('mymongoapp' will likely not be available).
  4. Select the same region as the MongoLab add-on you provisioned above.
  5. Click Create Web Site.
  6. When the web site creation completes, click the web site name in the web site list. The web site dashboard displays.
  7. Click Set up Git publishing under quick glance, and enter your desired git user name and password. You will use this password when pushing to your web site (in step 9).
  8. If you created your web site using the steps above, the following command will complete the process. However, if you already have more than one Windows Azure web site, you can skip the above steps and create a new web site using this same command. From your tasklist project directory:
    azure site create myuniquesitename --git

    Replace 'myuniquesitename' with the unique site name for your web site. If the web site is created as part of this command, you will be prompted for the datacenter that the site will be located in. Select the datacenter geographically close to your MongoLab database.

    The --git parameter will create:

    •  local git repository in the tasklist folder, if none exists.
    • a git-remote named 'azure', which will be used to publish the application to Windows Azure.
    • an iisnode.yml file, which contains settings used by Windows Azure to host node applications.
    • a .gitignore file to prevent the node-modules folder from being published to .git.
  1. Once this command has completed, you will see output similar to the following. Note that the line beginning with Created web site at contains the URL for the web site.
    info:   Executing command site create
    info:   Using location southcentraluswebspace
    info:   Executing `git init`
    info:   Creating default web.config file
    info:   Creating a new web site
    info:   Created web site at
    info:   Initializing repository
    info:   Repository initialized
    info:   Executing `git remote add azure`
    info:   site create command OK
  2. Use the following commands to add, and then commit files to your local Git repository:
    git add .
    git commit -m "adding files"
  3. Push your code:
    git push azure master

    When pushing the latest Git repository changes to the Windows Azure Web Site, you must specify that the target branch is master as this is used for the web site content. If prompted for a password, enter the password you created when you set up git publishing for your webs site above.

    You will see output similar to the following. As the deployment takes place Windows Azure will download all npm modules.

    Counting objects: 17, done.
    Delta compression using up to 8 threads.
    Compressing objects: 100% (13/13), done.
    Writing objects: 100% (17/17), 3.21 KiB, done.
    Total 17 (delta 0), reused 0 (delta 0)
    remote: New deployment received.
    remote: Updating branch 'master'.
    remote: Preparing deployment for commit id 'ef276f3042'.
    remote: Preparing files for deployment.
    remote: Running NPM.
    remote: Deploying Web.config to enable Node.js activation.
    remote: Deployment successful.
     * [new branch]      master -> master

You're almost done!

Configure your environment

Remember process.env.CUSTOMCONNSTR_MONGOLAB_URI in the code? We want to populate that environment variable with the value provided to Windows Azure during your MongoLab database provisioning.

Get the MongoLab connection string

When you provision a MongoLab database, MongoLab transmits a connection URI to Windows Azure in MongoDB's standard connection string format. This value is used to initiate a MongoDB connection through your choice of MongoDB driver. For more information about connection strings, see Connections at This URI contains your database user name and password. Treat it as sensitive information and do not share it.

You can retrieve this URI in the Windows Azure Portal using the following steps:

  1. Select Add-ons.
  2. Locate your MongoLab service in your add-on list.
  3. Cick the name of your add-on to reach the add-on page.
  4. Click Connection Info.
    Your MongoLab URI displays:
  5. Click the clipboard button to the right of the MONGOLAB_URI value to copy the full value to the clipboard.

Add the connection string to the web site's environment variables

While it's possible to paste a MongoLab URI into your code, we recommend configuring it in the environment for ease of management. This way, if the URI changes, you can update it through the Windows Azure Portal without going to the code.

  1. In the Windows Azure Portal, select Web Sites.
  2. Click the name of the web site in the web site list.
    The Web Site Dashboard displays.
  3. Click Configure in the menu bar.
  4. Scroll down to the Connection Strings section.
  5. For Name, enter MONGOLAB_URI.
  6. For Value, paste the connection string we obtained in the previous section.
  7. Select Custom in the Type drop-down (instead of the default SQLAzure).
  8. Click Save on the toolbar.
    Note: Windows Azure adds the CUSTOMCONNSTR_ prefix to this variable, which is why the code above references CUSTOMCONNSTR_MONGOLAB_URI.


Run azure site browse from your project directory to automatically open a browser, or open a browser and manually navigate to your web site URL (


Manage the database

Congratulations! You've just launched a Node.js application backed by a MongoLab-hosted MongoDB database! Now that you have a MongoLab database, you can contact with any questions or concerns about your database, or for help with MongoDB or the node driver itself. Good luck out there!

To access the MongoLab UI, do the following:

  1. Select Add-ons.
  2. Locate your MongoLab service in your list of add-ons.
  3. Click the name of your add-on to reach the add-on page.
  4. Click Manage.
    A new browser tab opens, displaying the MongoLab database home page:

From here you can select a specific collection and drill down to individual documents. Log out when you are finished.

Congratulations! You've just launched a Node.js application backed by a MongoLab-hosted MongoDB database! Now that you have a MongoLab database, you can contact with any questions or concerns about your database, or for help with MongoDB or the node driver itself.

Good luck out there!