Building A Node.js Based REST API Using Mongoose Node Module

In this article, we will be see how to build a simple and elegant REST based API with MongoDB backend. We are going to use Node.js and Mongoose node module to code a demo application for managing the book resource in MongoDB.

The demo application is based on the following code sample:

The following node modules are used in developing the demo app.

  1. Mongoose – A node.js MongoDB node module. It’s used for connecting, fetching and saving models in DB.

  2. Express – It’s a web framework internally make use of core node.js HTTP module. It abstracts and hides the complexities of creating and managing the web server.

  3. Body-Parser – A body parser is a middleware component used for parsing the incoming data in HTTP Request and makes all the data available as part of the request body. For more information on body-parser, please take a look into the following link.

Let us consider a scenario of managing the book information in MongoDB. We are going to perform the CRUD (create, read, update and delete) operation on the Book model.

We are building a simple REST based API for accessing the book information stored in MongoDB. Later, you will see how to set up routes for accessing the book resource. It’s all part of the express configuration which you will be seeing shortly.

Getting started

Before we code the sample application, we will have to make sure and install the following:

  1. Mongo DB – We are making use of MongoDB as our backend store. Please download and install the same by the following link.

  2. Postman – It’s a tiny Google chrome extension that we are using it to test our REST based API’s. Open up chrome and install “Postman” extension. You can install the same from Postman.

    Note – After installing, make sure to run the MongoDB, say by executing “mongod.exe” from command prompt.

Defining the Book Model

The following is the code snippet where you can see how we are defining the “Book” model. Firstly, we need to import mongoose Node.js module and then create a schema for our book model. The module exports let's us to access our book model using “require”.

  1. var mongoose = require('mongoose'),  
  2.     Schema = mongoose.Schema;  
  3. var bookSchema = new Schema(  
  4. {  
  5.     name: String,  
  6.     isbn:  
  7.     {  
  8.         type: String,  
  9.         index: true  
  10.     },  
  11.     author: String,  
  12.     pages: Number,  
  13.     description:  
  14.     {  
  15.         type: String  
  16.     },  
  17.     added_date:  
  18.     {  
  19.         type: Date,  
  20.         default: Date.now  
  21.     }  
  22. });  
  23. var book = mongoose.model('book', bookSchema);  
  24. module.exports = {  
  25.     Book: book  
  26. };  
Coding the Book Controller

Now let us code the book controller to have the following functionality.
  1. All – Select all books from Mongo DB.
  2. Select – Select the specified book from Mongo DB.
  3. Create – Creates a new book based on our Book model.
  4. Update – Updates the existing book based on the unique ID created by MongoDB.
  5. Delete – Deletes the book item from MongoDB based on the unique ID created by MongoDB.

Running the demo app

Please download the code sample attached in this article and follow the below instructions.

  1. Open up command prompt and navigate to the sample directory.

  2. Type “npm install” and hit enter. It basically reads the package.json to understand the dependencies and install the same so you should be seeing a folder “node_modules” with all dependent node modules.

  3. Type "node app" and hit enter to run application.

Fetch all Books

Here’s the code snippet of our “all” method. You can notice below, we are getting all “books” in MongoDB without applying the filter conditions. If the fetch goes well, then return all books, else we will be returning a message with the error description.

  1. var all = function (req, res)  
  2. {  
  3.     Book.find(  
  4.     {}, function (err, books)  
  5.     {  
  6.         if (!err)  
  7.         {  
  8.             res.json(200,  
  9.             {  
  10.                 books: books  
  11.             });  
  12.         }  
  13.         else  
  14.         {  
  15.             res.json(500,  
  16.             {  
  17.                 message: err  
  18.             });  
  19.         }  
  20.     });  
  21. }  
Here’s the snapshot of how getting all the books from Mongo DB works. As of now, we are having only one book and that’s created using HTTP POST which we will be seeing next.

Fetch all Books

Create Book

The following is the code snippet for creating a book via HTTP POST. The function requires two parameters, the request and response. We will be capturing all the book related info from the request body. At first, we are checking whether there exists any book filter by the ISBN number. Create a new book if we don’t have an error or if there are no such existing books in our DB.

In order to create a new book, all we have to do is, create a new instance of our Book model and set all the properties so that we can make a call to “save” method.
  1. var create = function (req, res)  
  2. {  
  3.     var name = req.body.name;  
  4.     var isbn = req.body.isbn;  
  5.     var author = req.body.author;  
  6.     var pages = req.body.pages;  
  7.     var description = req.body.description;  
  8.     var added_date = req.body.added_date;  
  9.     var book = req.body;  
  10.     console.log('Adding Book: ' + JSON.stringify(book));  
  11.     Book.findOne(  
  12.     {  
  13.         isbn: isbn  
  14.     }, function (err, exisiting_book)  
  15.     {  
  16.         if (!err && !exisiting_book)  
  17.         {  
  18.             var book = new Book();  
  19.             book.name = name;  
  20.             book.isbn = isbn;  
  21.             book.author = author;  
  22.             book.pages = pages;  
  23.             book.description = description;  
  24.             book.added_date = added_date;  
  25.             book.save(function (err)  
  26.             {  
  27.                 if (!err)  
  28.                 {  
  29.                     res.json(201,  
  30.                     {  
  31.                         message: "Book created with name: " + book.name  
  32.                     });  
  33.                 }  
  34.                 else  
  35.                 {  
  36.                     res.json(500,  
  37.                     {  
  38.                         message: "Could not create a Book. Error: " + err  
  39.                     });  
  40.                 }  
  41.             });  
  42.         }  
  43.         else if (!err)  
  44.         {  
  45.             res.json(403,  
  46.             {  
  47.                 message: "Book already exists! please update instead of creating one."  
  48.             });  
  49.         }  
  50.         else  
  51.         {  
  52.             res.json(500,  
  53.             {  
  54.                 message: err  
  55.             });  
  56.         }  
  57.     });  
  58. }  
Here’s the snapshot of the Postman tool showing how to create a new book by making an HTTP POST Request by passing in the raw book JSON data.

Create Book

Select Book

Let us now see how to select an existing book from MongoDB. The following is the code snippet for the same. We are going to find the book by ID. If we find one and has no errors while fetching the data, then we return the selected book info with the response code 200, else we are going to handle all the error conditions.
  1. var select = function (req, res)  
  2. {  
  3.     var id = req.params.id;  
  4.     console.log('Selecting Book: ' + id);  
  5.     Book.findById(id, function (err, book)  
  6.     {  
  7.         if (!err && book)  
  8.         {  
  9.             res.json(200, book);  
  10.         }  
  11.         else if (err)  
  12.         {  
  13.             res.json(500,  
  14.             {  
  15.                 message: "Error loading workout." + err  
  16.             });  
  17.         }  
  18.         else  
  19.         {  
  20.             res.json(404,  
  21.             {  
  22.                 message: "Book not found."  
  23.             });  
  24.         }  
  25.     });  
  26. }  
Here’s the snapshot, where you can see how we are selecting a book by its ID (which is nothing but a unique ID generated by MongoDB).

Select Book

Update Book

The following is the code snippet for updating an existing book in MongoDB. The code must be familiar to you by now. It looks exactly like “create” functionality. We are going to update the book, if we already have one, else we report an error stating, we are unable to find one.

Note – In order to update the book information, we have to make an HTTP PUT Request passing in the book information as a JSON data in the HTTP Request body.
  1. var update = function (req, res)  
  2. {  
  3.     var name = req.body.name;  
  4.     var isbn = req.body.isbn;  
  5.     var author = req.body.author;  
  6.     var pages = req.body.pages;  
  7.     var description = req.body.description;  
  8.     var book = req.body;  
  9.     console.log('Updating Book: ' + JSON.stringify(book));  
  10.     Book.findOne(  
  11.     {  
  12.         isbn: isbn  
  13.     }, function (err, book)  
  14.     {  
  15.         if (!err && book)  
  16.         {  
  17.             book.name = name;  
  18.             book.isbn = isbn;  
  19.             book.author = author;  
  20.             book.pages = pages;  
  21.             book.description = description;  
  22.             book.save(function (err)  
  23.             {  
  24.                 if (!err)  
  25.                 {  
  26.                     res.json(200,  
  27.                     {  
  28.                         message: "Book updated: " + name  
  29.                     });  
  30.                 }  
  31.                 else  
  32.                 {  
  33.                     res.json(500,  
  34.                     {  
  35.                         message: "Could not update book. " + err  
  36.                     });  
  37.                 }  
  38.             });  
  39.         }  
  40.         else if (!err)  
  41.         {  
  42.             res.json(404,  
  43.             {  
  44.                 message: "Could not find book."  
  45.             });  
  46.         }  
  47.         else  
  48.         {  
  49.             res.json(500,  
  50.             {  
  51.                 message: "Could not update book." + err  
  52.             });  
  53.         }  
  54.     });  
  55. }  
The following is the snapshot where you can see, we are making an HTTP Put request to update book info.

history Image

Remove Book

The following is the code snippet for deleting an existing book in Mongo DB. In order to remove the book, first we have to search one by ID. If we find one, then we are making a call to “remove” method and then send a message back to the user stating the book has been removed. Make sure to handle all errors while removing the book.
  1. var remove = function (req, res)  
  2. {  
  3.     var id = req.body.id;  
  4.     console.log('Removing Book: ' + id);  
  5.     Book.findById(id, function (err, book)  
  6.     {  
  7.         if (!err && book)  
  8.         {  
  9.             book.remove();  
  10.             res.json(200,  
  11.             {  
  12.                 message: "Book removed."  
  13.             });  
  14.         }  
  15.         else if (!err)  
  16.         {  
  17.             res.json(404,  
  18.             {  
  19.                 message: "Could not find book."  
  20.             });  
  21.         }  
  22.         else  
  23.         {  
  24.             res.json(403,  
  25.             {  
  26.                 message: "Could not delete book. " + err  
  27.             });  
  28.         }  
  29.     });  
  30. }  
Here’s the snapshot of the Postman tool, where you can see we are making an HTTP DELETE Request by passing in the book ID. You can also select “form-data” from the following option.

local host image

Now let us take a look into the express configuration. The following is the partial code snippet where we are creating an “app” object of type express and then set the port to use a default “3000”. You can also notice other settings such as to use body parser JSON, method override, router, etc. is all set.
  1. var app = express();  
  2.   
  3. app.configure(function(){  
  4. app.set('port', process.env.PORT || 3000);  
  5. app.use(express.logger('dev'));  
  6. app.use(bodyParser.json());  
  7. app.use(express.methodOverride());  
  8. app.use(app.router);  
  9. // parse application/x-www-form-urlencoded  
  10. app.use(bodyParser.urlencoded({ extended: false }))  
  11. });  
  12.   
  13. app.configure('development', function(){  
  14. app.use(express.errorHandler());  
  15. });  
Here’s the code snippet where you can see how we are configuring the routes for HTTP verbs. At first, we need to import and get the “Book” model. Then we need to import the book controller so we can set the export methods to our express “app” object. We have to explicitly specify the method to be called for GET, POST, PUT, DELETE, etc.  
  1. var Book = require('./models/book').Book;   
  2. var bookController = require('./controller/bookController')(Book);  
  3.   
  4. app.get('/books', bookController.all);  
  5. app.get('/books/:id', bookController.select);  
  6. app.post('/books', bookController.create);  
  7. app.put('/books', bookController.update);  
  8. app.del('/books', bookController.delete);   
Here’s how we are creating a MongoDB connection by importing the mongoose node module.
  1. var mongoose = require('mongoose');  
  2. mongoose.connect('mongodb://localhost/library');  
Let us see how to create a HTTP Server to listen to a specific port so it can handle the client request. The following is the code snippet for the same.
  1. http.createServer(app).listen(app.get('port'), function(){  
  2.    console.log("Express server listening on port %s in %s mode.", app.get('port'), app.settings.env);  
  3. });  
Conclusion

We have seen how to build a simple REST based API for managing the MongoDB entities. There’s a great potential and benefits that one can get in learning and using Node.js to build useful APIs and applications.