DotNetCurry Logo

Using Node.js, Express and MongoDB (MEAN stack) in an ASP.NET MVC application

Posted by: Mahesh Sabnis , on 5/28/2015, in Category Node.js
Views: 22186
Abstract: In this article we will learn how to create REST APIs using Node.js, MongoDB and Express (MEAN Stack) and then consume it in an ASP.NET MVC application

Today’s web applications have undergone a paradigm shift from being a stateless request-response implementation where only the client initiates communication; to being asynchronous real-time two-way channel, in which both the client and server can initiate communication. Meanwhile during this shift, JavaScript has quietly become omnipresent, and is used in websites, modern NoSQL databases, complicated mobile apps and even on servers.

Node.js was born somewhere in between the intersection of these trends and provided a core library to build network applications that allowed the server to make the best use of the available I/O in a non-blocking fashion. This library fits well in this era of modern apps which consists of a thick client built with modern JavaScript frameworks like Angular and Backbone, and a thin backend layer represented by the REST API.

In this article we will learn how to create REST APIs using Node.js, MongoDB and Express and then consume it in an ASP.NET MVC application.

Let us quickly introduce these technologies for those who are new to it.

This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free .NET tutorials from experts

Node.js

Node is a platform built on Google’s V8 JavaScript Runtime for building fast, scalable network applications, with ease. It uses non-blocking I/O and event-driven model. Before using Node.js in our application, it is important to understand some important features of it.

Traditionally web applications hosted on the servers spin up a process for each incoming request. This is an expensive operation both in terms of CPU and memory utilization. The following diagram illustrates the traditional web server behavior.

traditionalwebserver

This mechanism makes use of threads from a thread pool to manage incoming requests from each user. The server assigns a separate thread for each incoming request and uses the thread for the entire lifecycle of the request. The thread for each request keeps on utilizing resources of the server. This is an expensive approach, as it involves a lot of processing and resources. Here please note that unless the async request processing is not configured, e.g. in case of ASP.NET 4.5 the async Http handler; we cannot expect any improvement in resource utilization.

Node.js on the other hand uses event loop, which runs under a single thread. JavaScript runtime has a message queue which stores the list of messages to be processed with their associated callback functions. These messages are actually I/O calls with the callback registered with it. As soon as the I/O operation is completed, the associated callback is pushed in the event loop and executed. So despite of being "single threaded", there are an arbitrary number of operations that Node can handle in the background.

We can see the event loop in action in the following figure:

nodejseventloop

All the requests to be processed go into a single thread and hence result in less memory utilization, and because of the lack of the thread context switching, the CPU utilization is also less. This makes Node.js effective in data intensive applications.

Node.js Modules

Node.js ships with a number of built-in modules which provides core set of features to develop Node.js based solutions. Node.js modules are always loaded by passing their identifier to the require() function. Node has three kinds of module: core modules, file modules and external node modules.

File based modules in Node.js

The File-Based module system of Node.js has the following specifications:

· Each file is its own module

· Each file uses module variable to access the module definition

· module.export is used to determine the export of the current module.

The require() function of Node.js is the way to import modules into the current file.

e.g. require(‘../foldername/file’)

The above example will load the modules exported from the file under the foldername in Node applications.

Facts about Node.js File-Based Module

Modules can be loaded conditionally e.g. use if condition

if(somecondition){
  var mod = require(‘/moduleFIle’)
}

In this case the require function will load the module when the condition is satisfied.

  • The require function will block the execution unless the module is not completely loaded. This will make sure that the required functionality from the module will always be available to the caller.
  • Once the require function loads the module, it will be cached. The next time when the call is made to the require function with the same module, it will be loaded from the cache.
  • Once the module is loaded they can share the state across the context.
  • To export content from the module, Node.js uses module.exports. This empty object is by default available to all module in Node.js. e.g. module.exports={};

Node.js Core Modules

The Node.js core modules can still be consumed using the require function. The only difference here is that unlike the file-based modules, we directly pass the name of the module to the require function. The following is the list of Node.js core modules:

Path - The path module provides useful string transformations while working with the file system. This helps to eliminate inconsistencies in handling file system paths.

E.g. var path=require(‘path’);

Fs - The fs module provides an access to the file system. This has functions for renaming files, reading files, writing files, deleting files, etc.

E.g. var fs = require(‘fs’);

OS - The os module provideS access to some of the operating system functionality e.g. memory usage, free memory etc.

E.g. var os = require (‘os’);

In Node.js, module gets loaded based on its path. If the node module is specified without a path and if this module is not the core module, then Node looks for the module in the node_modules folder. If the module is located in this folder, then it will be loaded from here, else Node will search through the parent directory of node_modules.

External Modules

Apart from the Node.js core modules, there are various modules which provides rich functionality and are available to Node via third party sources. There are modules for relational and document databases, testing modules and many more. Developers can create their modules and upload on GitHub. External node modules can be loaded using the command line utility:

npm install 

or

npm install express

This will install the express module. Express.js is a middleware module. It is a minimal and flexible Node.js web application framework which provides several features like HTTP utilities for requests/responses and routing. In our application we will be using this framework for making HTTP GET, POST calls. More information about express can be obtained from here.

In the following application, we will be using this module. Once this module is installed, it will be available from the application’s local node_modules directory.

Now that we have gone through the basics of Node.js modules, it is time for us to create Node.js applications in .NET.

Developing a REST API with Node.js and Consume it in an ASP.NET MVC application

In this section, we will create a REST API using Node.js and then consume this API in an ASP.NET MVC application. To implement this solution, we will use the Free Visual Studio 2013 Community Edition. Node.js templates can be added to Visual Studio 2013 using Node.js tools for Visual Studio (NTVS). Once this extension is installed, Visual Studio will show Node.js templates as shown here:

nodetemplate

Our application will make use of MongoDB to store data. We can install MongoDB for windows by downloading it from this link. We need to install and configure MongoDB using the steps from the link here. Mongo can be installed in the %Program Files% folder and the MongoDB folder inside it. Using mongod –dbpath command, a connection with the MongoDB can be started as shown here:

mongodb

Using mongo command from the command prompt, the MongoDB shell can be connected with the default test database as shown in the following figure.

dbconnect

The New database can be created using the command use

empdb

The command use EmployeeDB creates a new database named EmployeeDB.

Step 1: Open Visual Studio and create a new blank Node.js console application and name it ‘NG_EXP_Node’ as shown in the following figure.

nodejs-project

This step will create an app.js file by default in the project.

Step 2: Since we will be using MongoDB, Express and Mongoose in the project, we need to install these packages first.

The Mongoose npm package allows to connect to MongoDB and helps to define the schema for storing data in MongoDB. This package also provides functions for performing CRUD operations against MongoDB.

Right-click on the project and select the Install new npm packages….option which brings up the package window. Note that if you are doing this for the first time, it will first list all packages. Luckily the window has a Search for package text box using which the necessary packages can be searched. Add the packages as shown in the following figure:

Express.js

express

Click on Express and click on ‘Install Package’ to install the Express package.

MongoDB

mongo

This is the driver for the MongoDB database access.

Mongoose

mongose

This will install the Mongoose npm package.

Body Parser

bodyparser

Body parser is a tool that gives you easy access to values submitted using a form. After these packages are added, the package.json file in the project will be updated with the following entries:

{
  "name": "NG_EXP_Node",
  "version": "0.0.0",
  "description": "NG_EXP_Node",
  "main": "app.js",
  "author": {
    "name": "Mahesh",
    "email": ""
  },
  "dependencies": {
    "body-parser": "^1.12.1",
    "bson": "^0.2.19",
    "express": "^4.12.2",
    "mongodb": "^1.4.34",
    "mongoose": "^3.8.25"
  }
}

Step 3: In the project, add a new JavaScript file named ReadWrite.js with the following code:

var mongooseDrv = require('mongoose'); //Get the Mongoose Driver
connection with the MongoDB


mongooseDrv.connect('mongodb://localhost/EmployeeDB');
var db = mongooseDrv.Connection; //The Connection 

if (db == 'undefined') {
    console.log("The Connecion issues");
}

//The Schema for the Data to be Stored
var EmployeeInfoSchema = mongooseDrv.Schema({
    EmpNo: String,
    EmpName: String,
    Salary: String,
    DeptName: String,
    Designation: String
});

var EmployeeInfoModel = mongooseDrv.model('EmployeeInfo', EmployeeInfoSchema);


//retrieve all records from the database 
exports.get = function (req, resp) {
    EmployeeInfoModel.find().exec(function (error, res) {
        if (error) { 
            resp.send(500, {error:error});
        } else { 
            resp.send(res);
        }

    }); 
};

//Add a new Record in the Employee Model
exports.add = function (request, response) {
  
    var newEmp = { EmpNo: request.body.EmpNo,EmpName: request.body.EmpName,Salary: request.body.Salary,DeptName: request.body.DeptName,Designation: request.body.Designation};
    EmployeeInfoModel.create(newEmp, function (addError, addedEmp) {
        if (addError) {
            response.send(500, { error: addError });
        }
        else {
            response.send({ success: true, emp: addedEmp });
        }
    });
};

The above JavaScript code uses the Mongoose driver to connect to the EmployeeDB database created in MongoDB. This also defines the EmployeeInfoSchema object containing the schema for storing Employee information. The methods get() and add() are used to read and write data received from the client application respectively.

Step 4: In the project, add the following code in app.js to load the necessary modules for Http utilities and REST APIs.

var body_Parser = require('body-parser'); //Load Modules for bodyparser
var path = require('path'); //Load 'path' the File base module 
var express = require('express'); //Load express module
var http = require('http'); //Load Http module for Http operation

var app = express(); //The Express object

app.use(body_Parser());

var rwOperation = require('./ReadWrite.js'); //Load the File

var communicationPort = 8080; //The Communication port

//The REST API

app.get('/EmployeeList/api/employees', rwOperation.get);

app.post('/EmployeeList/api/employees', rwOperation.add);


app.listen(communicationPort);

This code loads express module for creating REST APIs. The get() and post() methods on the express application object are used to expose REST APIs to perform HTTP GET and POST methods respectively.

Step 5: Open the command prompt with Admin (Run as Administrator) rights. Navigate to the project folder and run the following command.

:>node app.js 

This will start the Node.js environment.

Step 6: In the same solution, add a new empty ASP.NET MVC application with the name Node_MVCClient. In this project, add JavaScript references for jQuery, Bootstrap and Angular.js using NuGet.

Step 7: In the Controllers folder, add a new empty MVC controller of the name NodeAppController. Scaffold an empty Index view from the Index method of this controller.

Step 8: In the Scripts folder add a new folder of name MyScripts. In this folder, add the following JavaScript files:

module.js

var app;
(function () {
    app = angular.module('mynodemodule',[]);
})();

service.js

app.service('mynodeservice', function ($http) {
    this.get = function(){
        var res = $http.get("http://localhost:8080/EmployeeList/api/employees");
        return res;
    }

    this.post = function (emp) {
        var res = $http.post("http://localhost:8080/EmployeeList/api/employees",emp);
        return res;
    }

   });

The above code defines methods for making a call to the REST APIs using Node.js application.

Controller.js

app.controller('mynodecontroller', function ($scope, mynodeservice) {

    //The Employee Object used to Post
    $scope.Employee = {
        _id:"",
        EmpNo: 0,
        EmpName: "",
        Salary: 0,
        DeptName: "",
        Designation:""
    }

    loaddata();
    //Function to load all records
    function loaddata() {
        var promise = mynodeservice.get();

        promise.then(function (resp) {
            $scope.Employees = resp.data;
            $scope.message = "Call is Successful ";
        }, function (err) {
            $scope.message = "Error in Call" + err.status
        });
    };

    //Function to POST Employee
    $scope.save = function () {
        var promisePost = mynodeservice.post($scope.Employee);

        promisePost.then(function (resp) {
            $scope.message = "Call is Successful";
            loaddata();
        }, function (err) {
            $scope.message = "Error in Call" + err.status
        });
    };

    $scope.clear = function () {
        $scope.Employee.EmpNo = 0;
        $scope.Employee.EmpName = "";
        $scope.Employee.Salary = 0;
        $scope.Employee.DeptName = "";
        $scope.Employee.Designation = "";
    };

});

The above code contains functions for reading all data using REST APIs and performing POST operations.

Step 9: In the Index.cshtml add the following markup



    
    
    
    
    
    




    

Index

EmpNo
EmpName
Salary
DeptName
Designation
ID EmpNo EmpName Salary DeptName Designation
{{Emp._id}} {{Emp.EmpNo}} {{Emp.EmpName}} {{Emp.Salary}} {{Emp.DeptName}} {{Emp.Designation}}
{{Message}}

This markup contains Angularjs databinding using various directives.

Run the application and you should get the following result:

result

Enter values in the TextBoxes and click on the Save button. The table will display the newly added record.

CONCLUSION

This article demonstrated how Node.js provides server-side JavaScript features for REST APIs and how it can be consumed by any client application. This article aimed at helping ASP.NET developers learn the essentials of Node.js web development using the MEAN stack.

Download the entire source code from GitHub at bit.ly/dncm18-nodejsdotnet

  • Please Share this article if you think it was worth reading. Thanks!
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a Microsoft MVP having 14 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
comments powered by Disqus