Implementing RESTFul Services with Node.js and MongoDB


In my previous post, I shared a new version of the Employee Directory sample application. By default, the application uses an in-memory data store to provide a “download and run” experience (no need to set up a server or a database). In this post, I’ll show how to replace the in-memory data store with RESTful services powered by Node.js, MongoDB and the Express framework.

If you are not using the Employee Directory sample application, you can still use this post on its own to learn how to implement RESTful services with Node.js, MongoDB and the Express framework.

Step 1: Install Node.js

If it’s not already installed on your system, follow the steps below to install Node.js:

  1. Go to http://nodejs.org, and click the Install button.
  2. Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm. At this point node.js is ready to use.

Step 2: Install MongoDB

If MongoDB is not already installed on your system, refer to the MongoDB QuickStart for platform-specific installation instructions. Here are some quick steps to install MongoDB on a Mac:

  1. Go to http://www.mongodb.org/downloads and download the latest OS X 64-bit production release (2.4.2 at the time of this writing).
  2. In Finder, double-click mongodb-osx-x86_64-2.4.2.tgz to extract its contents. (Alternatively you can use: tar -zxvf mongodb-osx-x86_64-2.4.2.tgz)
  3. Move the mongodb-osx-x86_64-2.4.2 folder to /usr/local (or another folder according to your personal preferences):
    sudo mv -n mongodb-osx-x86_64-2.4.2/ /usr/local/
    
  4. (Optional) Create a symbolic link to make it easier to access:
    sudo ln -s /usr/local/mongodb-osx-x86_64-2.4.2 /usr/local/mongodb
    
  5. Create a folder for MongoDB’s data and set the appropriate permissions:
    sudo mkdir -p /data/db
    sudo chown `id -u` /data/db
    
  6. Start mongodb
    cd /usr/local/mongodb
    ./bin/mongod
    

Step 3: Download the Code

The Node.js code for the Employee Directory RESTful services is available in this GitHub repository. Download it here and unzip the file anywhere on your file system.

Open server.js and routes/employee.js in a code editor. The RESTFul API is defined as follows:

Method URL Action
GET /employees Retrieve all employees
GET /employees?name=j Retrieve employees whose name includes the letter “j”
GET /employees/3 Retrieve employee with id=3
GET /employees/3/reports Retrieve employees that are direct reports of employee number 3
In routes/employee.js, the use of res.jsonp() makes the services work for both JSON and JSONP requests. If the request includes a query parameter named “callback”, a JSONP response is returned, otherwise, a regular JSON response is returned.

Step 4: Install dependencies (Express Framework and MongoDB driver)

Open package.json in a code editor and note that the application has two dependencies: the Express framework and the MongoDB driver. To install these dependencies, open a command line (terminal window), cd to the directory where you extracted the source code, and type:

npm install

Step 5: Start the server

Make sure MongoDB is started (Step 2 point 6 above) before you start your Node.js server as follows:

node server.js

Step 6: Testing the API in your Browser

Step 7: Test the API with the Employee Directory Client Application

  1. Download the source code for the Employee Directory client application available in this repository.
  2. Unzip the file anywhere on your file system.
  3. Open index.html in your code editor.
  4. Comment out the “model-in-memory.js” script, and uncomment the “model-jsonp.js” script to use the JSONP adapter that connects to your Node.js server.
  5. Make sure the MongoDB and Node.js servers are started
  6. Open index.html in a Browser and test the application
Because the templates of this application are loaded using XMLHTTPRequest, you will get a cross domain error (Access-Control-Allow-Origin) if you load index.html from the file system (with the file:// protocol). Make sure you load the application from a web server. For example: http://localhost/directory-backbone-bootstrap.

Related Post

Check out this post for another Node.js example with a more complete RESTful API including the ability to add, modify and delete items (POST, PUT, and DELETE HTTP methods).

4 Responses to Implementing RESTFul Services with Node.js and MongoDB

  1. Tristan February 26, 2014 at 5:47 am #

    Hi,

    How would i link this to an external MongoDB? I’ve tried lots of different methods and I cant work out where I would need to put the database URL/login data?

    Your tutorial was extremely good, I built my first ios app!

    Many thanks,
    tristan

  2. Ruth June 16, 2014 at 10:11 am #

    Hi, I wish to find employee by date created by date:

    I have the date in my mongo database as document “Time”

    I need help, I don’t seem to get it right
    Here is my code:

    exports.findDate = function(req, res) {
    var date = req.query["date"];
    db.collection(‘allemployees’, function(err, collection) {
    if (date) {
    collection.find({“Time”: new RegExp(date, “i”)}).toArray(function(err, items) {
    res.jsonp(items);
    });
    }

    else {
    collection.find().toArray(function(err, items) {
    res.jsonp(items);
    });
    }
    });
    };

    app.get(‘/employees’, wines.findDate);

    and I’. searching with http://localhost:3000/employees?date=06/16/2014

  3. http://www.youtube.com/watch?v=teIqRglpa-E July 10, 2014 at 10:59 am #

    And it’s not a doctor didn’t give you the risks associated with every procedure has certain options and rights.
    Go get it right now because I malpractice attorney want to
    talk about the breast lump. An experienced and
    knowledgeable professionals to hold the key in understanding whether or not this material
    has to agree yes.

Trackbacks/Pingbacks

  1. Scott Banwart's Blog › Distributed Weekly 204 - April 26, 2013

    [...] Implementing RESTFul Services with Node.js and MongoDB [...]

Leave a Reply