Step by Step building Node.js based REST API to perform CRUD operations on MongoDB.

Download Source Code of this post from GitHub here

Node.js is one of the greatest platform to create backend of the application. Does not matter whether you are creating a mobile app for iOS or Single Page Web application using Angular, you will need a backend for the application. Usually you perform databases operations, authentications, authorizations, logging etc. in the backend. I am sure, you have heard about the term MEAN stack. If you have not, MEAN stands for MongoDB, Express JS, Angular, and Node.js.

image

In the MEAN stack, you create backend of the application using MongoDB, ExpressJS and NodeJS. In this article, you will learn to create a REST API to perform CRUD operations on MongoDB. You will use ExpressJS and NodeJS to create the REST API.

In this post, you are going to create a REST API to preform CRUD operations.

image

From the client, you will perform operations such as GET, POST, PUT, and DELETE to perform CRUD operations. Therefore, to create a record, you will perform HTTP POST operation and pass data to be inserted in the body of the HTTP request.

image

At the end of this post you will have a working API running which will perform CRUD operations.

Installation

To follow along this post, make sure you have following software installed on your machine.

To configure MongoDB , after installation make sure that you have in your primary drive where OS is installed(C drive in most of the cases on Windows) a folder called data\db. If you do not have create this folder. By default, MongoDB look for this folder to work with. Also, make sure to start MongoDB server by running Mongod.exe command as shown in the image below, to work with this post

image

After successful installation, create a blank folder in which you will create the project. Give whatever name you wish to give this folder. I am calling it as Project folder.

Step 1: Install dependencies

In the project folder, add a file with name package.json. We are going to use npm (Node Package Manager) to install all the dependencies. Node Package Manager (npm) reads package.json file to install the dependencies in the project. Add the below code in package.json.


{
    "name": "product-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "body-parser": "~1.0.1",
        "cors": "2.8.1",
        "mongoose": "~3.6.13"
    }
}

In this, we are mentioning that, the project we are going to create will have following dependencies :

  • Express JS to create API routes.
  • Body parser to parse JSON data coming from the client.
  • CORS to enable the cross origin resource sharing support in your API.
  • Monogoose to work with MongoDB in NodeJS.

After updating package.json with above code, open the project in the command prompt and run the command npm install. I am assuming here that, you have already NodeJS installed on your system. If you haven’t installed it, click here and install.

Once you have successfully ran npm install command, you will find a node_modules folder which is created inside your project containing all the required dependencies to create REST API in NodeJS, performing CRUD operations on MongoDB.

Step 2: Create Model

When you work with RDBMS such as SQL Server or MySQL, you create model to perform CRUD operations on that particular table. MongoDB is a document-based database, and in this, you can insert, delete, update or read documents. MongoDB does not restrict you to create fixed model to perform database operations. However, to work with mongoose, you need a model. So, let us create a model of the document to perform CRUD operations.

In the project, add a file called product.js and create model with name Product as shown in the listing below :


var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
    title: String,
    price: Number,
    instock: Boolean,
    photo: String,
});
module.exports = mongoose.model('Product', ProductSchema);

As you might have noticed, Product model contains four properties of different data types.

Step 3: Create Server

In this step, we will create server for REST API. For creating a server, add a file in the project called server.js. Go back and examine package.json file, you will find that the value of main is set as server.js. Therefore, node server will look for server.js to start the server. We are going to put all the starting codes in the file.

To start with, in server.js, add the following required statements at the top of the file.

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

After importing all the required modules, create route, assign port, and use body parser to parse incoming JSON data. To do these, after last require statement add the codes listed below in server.js file.


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

In the above snippet, we are assigning port and creating the router. After this, at the end of the server.js file, add the code listed below :


app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

In the above snippet, you are enabling CORS support, configuring port for the API, and also configuring that REST API would be created on baseurl/api/{routename}. At this point, you have configured server for various API settings and assigned port to work with that. Keeping everything together, at the end of this step, server.js file will look like below:

Server.js


var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

// all other code will go here 

app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

Step 3: Connect to MongoDB server

In this step, you will connect application to MongoDB database server. To do this, just after router creation code (or at the place where there is a comment “all codes goes here”), add the code mentioned below:


mongoose.connect('mongodb://localhost:27017/products');

You are connecting to product database of MongoDB server. By default, MongoDB runs on the port 27017.

Note:

At this point, make sure that your MongoDB server is running on this port, otherwise you will get an exception when running the API. On Windows, to run the server- navigate to c:\program files\mongodb\server\3.4\bin on the command prompt and run the command mongod.exe. This command will start the MongoDB server. Here I am assuming that, you already have MongoDB installed. If you do not have, you can download and install MongoDB from here

Step 4: Creating the middle route

Let us start with writing a route, which will be called before any route. In this route, you can perform various operations such as :

  • Authentication
  • Authorization
  • Logging

In Express JS, you can very easily create this route by adding a “use route” as shown in the listing below:


router.use(function (req, res, next) {
    // do logging 
    // do authentication 
    console.log('Logging of request will be done here');
    next(); // make sure we go to the next routes and don't stop here
});

Make sure to add above code in server.js, just after the code you created in step 3.

Step 5: Creating Record

To create the record or insert a new document, you need to create a route for the POST operation. In REST API, convention is that, whenever client will perform the POST operation, a new record will be created. So, let us start with creating a route for the POST operation. To create that, just below the “use route” line of code, add the code mentioned below :


router.route('/products').post(function (req, res) {

   
});

The above route will be called, whenever client will perform HTTP POST operation on baseurl/api/products

Next, you need to write the code to insert data in the database. For that, you need to perform two operations :

  1. Create model object using the request body. If you remember, we have created a model in the step 2.
  2. Call the save function on model object to save the record in the database.

To do the above tasks, you need to modify POST route as shown below:


router.route('/products').post(function (req, res) {
    var p = new product();
    p.title = req.body.title;
    p.price = req.body.price;
    p.instock = req.body.instock;
    p.photo = req.body.photo;
    p.save(function (err) {
        if (err) {
            res.send(err);
        }
        res.send({ message: 'Product Created !' })
    })
});

Run and Test

To test the Create API, run the command

image

Now your API is running on the port 8090. To test the API, open POSTMAN and perform a POST operation on URL baseurl/api/products.

image

Beside the above configuration, in Headers, a content-type is added as application/json. When you click on send, if everything happens as expected, you will be getting the response from the API as shown in the image below:

image

You might be wondering, in which database product it has been created? In the previous steps, you connected to database “products”. So all the operations will be performed with Products database. Also in step 2, while creating a model, since we have not provided any collection name, record will be created in products (plural of model name product) collection.

Step 6: Fetching Records

To fetch records, you need to perform GET operation. To do so, add a get route to the API. A GET route could be added as shown in the listing below:


router.route('/products').get(function (req, res) {
    product.find(function (err, products) {
        if (err) {
            res.send(err);
        }
        res.send(products);
    });
});

In above listing, you are using mongoose ‘find function’ to fetch all the records from the MongoDB collection.

The above route will be called, whenever client will perform HTTP GET operation on baseurl/api/products. To test API, open POSTMAN and perform a GET operation on URL baseurl/api/products.

image

In Postman, you will find that, HTTP GET operation returns all the records. To return to a particular record on basis of ‘product_id’, add a new route to the API such that, whenever you perform GET operation with product_id as query parameter on the same URL, you will fetch a particular record.


router.route('/products/:product_id').get(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err)
            res.send(err);
        res.json(prod);
    });
});

To fetch a particular product, you are using mongoose findById() function which takes product_id as input parameter. To read input parameter from HTTP GET operation, we are using req.params property.

The above route will be called, whenever client will perform HTTP GET operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a GET operation on URL baseurl/api/products/{product_id}.

 

image

You will find that a particular product has been returned with matching product_id.

Step 7: Updating Record

To update a record, you need to perform HTTP PUT operation. While performing PUT operation,

  • Pass product_id need to be updated as query parameter.
  • Pass product object need to be updated as request body.

To perform PUT operation, create a PUT route as shown in the listing below:


router.route('/products/:product_id').put(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err) {
            res.send(err);
        }
        prod.title = req.body.title;
        prod.price = req.body.price;
        prod.instock = req.body.instock;
        prod.photo = req.body.photo;
        prod.save(function (err) {
            if (err)
                res.send(err);

            res.json({ message: 'Product updated!' });
        });

    });
});

So, what is going on in above code listing? These are the operations that need to be done to perform the updated operation.

  • Fetch product to be updated from the collection.
  • Update fetched product properties with the request body object properties.
  • Save the product to the collection using save method.

The above route will be called to update a particular product, whenever the client will perform HTTP PUT operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a PUT operation on URL baseurl/api/products/{product_id}. You need to pass product object to be updated in the body of the request as shown in the image below:

image

Step 8: Deleting Record

To delete a particular record, client needs to perform HTTP DELETE operation. To do this, create a route for delete operation.


router.route('/products/:product_id').delete(function (req, res) {

    product.remove({ _id: req.param.product_id }, function (err, prod) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Successfully deleted' });
    })

});

Client will pass product_id to be deleted in the query parameter. Note : Product remove method is used to remove a product from the collection.

The above route will be called to delete a particular product, whenever client will perform HTTP DELETE operation on baseurl/api/products/{product_id}. To test API, open POSTMAN and perform a DELETE operation on URL baseurl/api/products/{product_id} as shown in the image below:

image

You just created a full working REST API to perform CRUD operations on MongoDB using NodeJS. In next post, we will use this API with Angular application to complete an application using MEAN stack. Thanks for reading.

Download Source Code of this post from GitHub here

Introduction to Angular Components

A component is a main building block of an Angular  application, and an application may have any number of components. We can consider a component a particular view of the application with its own logic and data.

In AngularJS 1.0, there was the concept of controllers, $Scope, and directives to bind data and logic to the view or to create custom elements on the view. In Angular , components perform all the tasks that were performed by controllers, scopes and directives. Data, logic and custom elements can all be created or added to the page using components in Angular .

Angular 2 applications are built around components, and we can consider component as a view with its own:

  • Template
  • Application Data
  • Logic
  • Styles, and more

Let’s Create Our First Component

Let us start with creating a very simple component to display “Hello World” on the page.

appcomponent.component.ts

 

 

There are mainly three steps to create a component

  1. Create a class and export it. This class will contain data and the logic.
  2. Decorate the class with @component metadata. Basically, metadata describes the component and sets the value for different properties, so that a TypeScript class can be used as an Angular  component.
  3. Import the required libraries and modules to create the component.

Three steps discussed above can be visualized in the diagram below:

image

As you can see, the Angular  component consists of:

  • A TypeScript Class to hold data and the logic;
  • HTML template and styles to display data in the app. It is also called as a view, which is seen by the user on the screen to interact.
  • Metadata which defines the behavior of a component. Component metadata is applied to the class using the @Component decorator. Different behavior of the component can be passed as properties of the object, which is and input parameter of the @Component decorator.

Read full article on the Infragistics blog

What are Closures in JavaScript?

Read full article on the Infragistics Blog

A JavaScript closure is a function which remembers the environment in which it was created. We can think of it as an object with one method and private variables. JavaScript closures are a special kind of object which contains the function and the local scope of the function with all the variables (environment) when the closure was created.

image

To understand closures, first we need to understand SCOPING in the JavaScript. We can create a variable or a function in three levels of scoping,

  1. Global Scope
  2. Function or local scope
  3. Lexical scope

I have written in details about scoping here, but let’s take a brief walkthrough of scoping before getting into closures.

Scopes in JavaScript

As soon as we create a variable, it is in a Global Scope. So, if we have created a variable which is not inside any function, it is in a global scope.

Read full article on the Infragistics Blog

Different ways of injecting dependency in an AngularJS Application

When you start learning the very first characteristics of AngularJS, you may come across something called Dependency Injection (DI): the premise that AngularJS injects dependencies whenever an application needs them. As a developer, our task is only to pass the dependency to the module and everything else will be taken care by AngularJS.

To create a controller, we pass $scope object and other dependencies to the module’s controller function. For example, to create a ProductController, we are passing $scope object and Calculator service dependencies. As a developer our job is to pass the dependencies and AngularJS will inject them whenever the application needs them.

As a developer, we really don’t care about how AngularJS injects dependencies – we don’t need to know how the injection process works to develop applications.  However, it is better if we know different ways of passing dependencies. In AngularJS, dependencies can be passed in three possible ways. They are as follows:

  • Passing a dependency as Function Arguments
  • Passing a dependency as Array Arguments
  • Passing a dependency using the $inject service

Let us explore these options one by one.

Passing a dependency as a Function Argument

Perhaps most of the time you pass a dependency as a function argument, which is perfectly fine. For example, we pass a $scope object to create a controller as shown in the listing below:

Read full article on the Infragistics blog

What is a Provider () in AngularJS?

The provider() function allows us to create a configurable service where we can set input per application for the service created using the provider (). For example, if we need to set API key to access a service on the application level, we can set that in the module config and pass input to the provider using the $provide service. All the others ways to create services internally use the $provide service.

Creating a service using $provide service in module.config

Let us start by creating a very simple service using the provider() function.

	
app.config(function ($provide) {
    $provide.provider('globalsetting', function () {
        this.$get = function () {
            var appname = "Lawyer App";
            return {
                appName: appname
            };
        }
    })
});

Let’s explore what is going on in the above snippet. To create a service using provider, we need to use the $provide service. The provider function of the $provide service takes two parameters: the name of the service and the function. A provider function must have a $get function. To create a simple service using the provider(), we need to perform following five steps:

  1. Inject the $provide service in the app config method
  2. Create a provider using the provider() function
  3. Pass two parameters to the provider() function: the name of the service and a function
  4. The provider function must contain a $get function
  5. Return an object literal from the $get function

We can use the globalsetting service created using the provider by injecting it in a controller as shown in the listing below:

Read full article on the Infragistics blog