Building a Simple HTTP API using Node.js with MongoDB and Mongoose

In this post, I will demonstrate how to build a simple HTTP API using Node.js with NoSQL database MongoDB. This demo app will be using MongoDB object modeling tool Mongoose to connecting with MongoDB from the Node app. This demo app is a very basic level JSON based HTTP API which is not following any better practices and mainly created this sample demo for demonstrating Node.js and MongoDB using with Mongoose Node package.

Node.js and MongoDB for building REST JSON API

Node.js is a very powerful platform for building highly scalable REST based JSON APIs. A Node.js app with a NoSQL database MongoDB can provide great performance and better scalability. The latest speed up results for the MongoDB Native Driver for Node.js available from here. I am in the process of building highly scalable REST API on the Windows Azure platform using Node.js and MongoDB and will be put the samples on my Github repositories in future. 

Node packages

The following Node packages to be installed in the app in order to working the demo app.

Express is a web development module for Node.js. Mongoose is a Node.js ORM module for working with MongoDB database.

Creating Server and Connecting to MongoDB

The following code block will create the server using express module and connecting to the MongoDB database using the Mongoose.

   1:   //Creating server
   2:  var express = require('express')
   3:        , app = express.createServer()
   4:        , mongoose = require('mongoose');
   6:  //Connecting to MongoDB
   7:   mongoose.connect('mongodb://localhost/ProductDB');

Creating the Model using Mongoose

Let’s define the Model objects using the Mongoose

   1:  //Models using Mongoose
   2:   var Schema = mongoose.Schema
   3:   , ObjectId = Schema.ObjectID;
   5:   var Product = new Schema({
   6:     name : { type: String, required: true, trim: true }
   7:    ,unitPrice  : { type: Number, required: true }
   8:    ,itemsInStock  : { type: Number, required: true }
   9:    });    
  11:  var Category = new Schema({
  12:   name   : { type: String, required: true, trim: true }
  13:   ,description    :  { type: String, required: true, trim: true }  
  14:   ,products         : [Product]       
  15:   });    
  17:  var ProductCatalog = mongoose.model('Category', Category);

In the above code block, we have created the schema for Product and Category and Prodcut schema used as embedded document in the Category schema. We can define the Model using the mongoose.Model.

var ProductCatalog = mongoose.model('Category', Category);

Exposing the API methods

The following function returns the all product catalog information as a JSON string. The request for ‘/’ will return the all product catalog data.

   1:   //Get all product catalog 
   2:    app.get('/', function(req,res){    
   3:   ProductCatalog.find({}, function(error, data){
   4:              if(error){
   5:               res.json(error);
   6:              }
   7:              else if(data == null){
   8:               res.json('Empty data')
   9:              }
  10:              else{
  11:                res.json(data);
  12:              }
  14:          });
  15:      });

The following function returns the category information for a given category name. The request ‘/name’ will be executed the following API method.

   1:  //Get a specified category
   2:  app.get('/:name', function(req,res){    
   3:   ProductCatalog.findOne({ name: },
   4:      function(error, category){
   5:   if(error){
   6:        res.json(error);
   7:       }
   8:       else if(category == null){
   9:             res.json('Category not found!')
  10:       }
  11:    else{
  12:       res.json(category);    
  13:        }
  14:     });            
  15:    });

The request for '/addcategory/name/description' will be executed the following method and will add a new category to the MongoDB database.The method will return the added data as JSON.

   1:  app.get('/addcategory/:name/:description',
   2:   function(req, res){
   3:   var categoryData = {
   4:   name:
   5:    , description: req.params.description         
   6:  };
   8:  var category = new ProductCatalog(categoryData);
   9:   //Save data
  10: function(error, data){
  11:  if(error){
  12:   res.json(error);
  13:  }
  14:  else{
  15:  res.json(data);
  16:     }
  17:   });
  18:  });

Source Code

I have created a repository in Github for putting REST API samples. This is the first and basic level sample which can be download from here. This is a very introductory level post mainly used for demonstrating Node.js and MongoDB with Mongoose. I will update the source code repository with more samples.


Published Saturday, May 19, 2012 8:27 AM by shiju


No Comments

Leave a Comment