MEAN stack
MongoDB, Express, AngularJS, Node.js are abbreviated as MEAN. These are application development packs all by JavaScript. In this sample, we are going to use MSSQL Server instead of MongoDB.
With this application sample, we can create a new user, show all the users, modify user data, and also delete the user through API built with Express from the front-end using AngularJS.
Components
- MSSQL - SQL database
- Express - NodeJS Framework
- Angular - JavaScript frameworks for front-end
- Node.js - JavaScript Execution Environment (Server)
Dependencies
It’s highly recommended to review these previous posts to be able to follow this post.
Let’s create a database in MSSQL server for user data. After creating the database, execute the below query by using that DB.
- CREATE TABLE [dbo].[User](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](250) NULL,
- [Email] [nvarchar](250) NULL,
- [Phone] [nvarchar](50) NULL,
- CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- This will create a new table named “user”. After that we need to create some stored procedure for SQL operation, copy below script and execute those by pasting it in MSSql query window.
- CREATE PROCEDURE [dbo].[GetUsers]
- -- Add the parameters for the stored procedure here
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- -- Insert statements for procedure here
- SELECT * FROM [dbo].[User]
- END
- GO
- CREATE PROCEDURE [dbo].[GetUserById]
- @Id Int
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- -- Insert statements for procedure here
- SELECT * FROM [dbo].[User] WHERE Id = @Id
- END
- GO
- CREATE PROCEDURE [dbo].[PutUser]
- -- Add the parameters for the stored procedure here
- @Id INT,
- @Name NVarchar(250),
- @Email NVarchar(250),
- @Phone NVarchar(50)
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- -- Insert statements for procedure here
- Update [dbo].[User]
- SET [Name] = @Name,[Email] = @Email,[Phone] = @Phone
- WHERE [Id] = @Id
- END
- GO
- CREATE PROCEDURE [dbo].[SetUser]
- -- Add the parameters for the stored procedure here
- @Name NVarchar(250),
- @Email NVarchar(250),
- @Phone NVarchar(50)
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- -- Insert statements for procedure here
- INSERT INTO [dbo].[User]([Name],[Email],[Phone])
- VALUES(@Name,@Email,@Phone)
- END
- GO
- CREATE PROCEDURE [dbo].[DeleteUser]
- -- Add the parameters for the stored procedure here
- @Id Int
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- -- Insert statements for procedure here
- DELETE FROM [dbo].[User]
- WHERE [Id] = @Id
- END
- --Exec DeleteUser 1
- GO
We are done with the database work; let’s start with application development plan. We are going to start from our previous sample application.
Download it from GitHub, then open the application using Visual Studio 2017. We need to install two more packages to fulfill our requirements.
- mssql - Microsoft SQL Server client for Node.js
- body-parser - Node.js body parsing middleware
Server Side - Installation
Right-click on project and open Command Prompt here.
Run this command for installing MSSQL.
npm install mssql
Run this command for installing body-parser.
npm install body-parser
After completing those installations, we need to add those to our Node server. Here, we have added it by enabling the following command.
var bodyParser = require("body-parser");
Then, we have used the following code.
- //Body Parser Middleware
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: true }));
Operations are going to be performed through APIs using Express route. Let’s get started with creating the API process.
APIs
Let’s create a data service to perform the operations in the database. Add a common dbService.js file to serve the requests, like the below image.
Open the newly added JS file, then add this line.
- var mssql = require('mssql');
This means that we are requiring mssql module by require() function to load the source code in a new function.
After that, we are adding the database server connection configuration.
- var dbConfig = {
- user: "sa",
- password: "sa@12345",
- server: "DESKTOP-80DEJMQ",
- database: "dbNode",
- pool: {
- max: 10,
- min: 0,
- idleTimeoutMillis: 30000
- }
- };
As we can see, the max pool is 10 and the min is 0 and the timeout is in milliseconds before closing an unused connection, which is default.
Get more details on Pool: https://github.com/coopernurse/node-pool
- var executeQuery = function (sql, res) {
- const conn = new mssql.ConnectionPool(dbConfig);
- conn.connect().then(function () {
- const req = new mssql.Request(conn);
- req.query(sql).then(function (data) {
- res(data);
- }).catch(function (err) {
- res(null, err);
- })
- }).catch(function (err) {
- res(null, err);
- })
- }
Connections
- const conn = new mssql.ConnectionPool(dbConfig);
We are creating a SQL connection object using ConnectionPool.
Request
- const req = new mssql.Request(conn);
Then, we are executing the request using the global connection pool.
Get more details on connection: https://www.npmjs.com/package/mssql#connections-1
Finally, we are exporting the module for another module call.
- module.exports = {
- executeQuery
- }
Let’s create a specific data service using Express router. Create a new JS file, then add those code snippets below to the newly added file.
- var express = require('express');
- var router = express.Router();
- var dbService = require('../dbService');
- //GET API
- router.get("/api/user/getAll", function (req, res) {
- var query = "GetUsers";
- dbService.executeQuery(query, function (data, err) {
- if (err) {
- throw err;
- } else {
- res.send(data.recordset);
- }
- res.end();
- });
- });
- // GET API
- router.get("/api/user/getUser/:id", function (req, res) {
- var query = "[GetUserById] " + parseInt(req.params.id) + "";
- dbService.executeQuery(query, function (data, err) {
- if (err) {
- throw err;
- } else {
- res.send(data.recordset);
- }
- res.end();
- });
- });
- //POST API
- router.post("/api/user/setUser", function (req, res) {
- var query = "[SetUser] '" + req.body.Name + "', '" + req.body.Email + "', '" + req.body.Phone + "'";
- dbService.executeQuery(query, function (data, err) {
- if (err) {
- throw err;
- } else {
- res.send(data.recordset);
- }
- res.end();
- });
- });
- //PUT API
- router.put("/api/user/putUser", function (req, res) {
- var query = "[PutUser] " + parseInt(req.body.Id) + ", '" + req.body.Name + "','" + req.body.Email + "', '" + req.body.Phone + "'";
- dbService.executeQuery(query, function (data, err) {
- if (err) {
- throw err;
- } else {
- res.send(data.recordset);
- }
- res.end();
- });
- });
- //DELETE API
- router.delete("/api/user/deleteUser/:id", function (req, res) {
- var query = "[DeleteUser] " + parseInt(req.params.id) + "";
- dbService.executeQuery(query, function (data, err) {
- if (err) {
- throw err;
- } else {
- res.send(data.recordset);
- }
- res.end();
- });
- });
- module.exports = router;



Uttam ChaturvediPosted Feb 27, 2018, 8:27 AM
Nice article.. Thanks for sharing
Hiten PandyaPosted Feb 27, 2018, 7:54 AM
Thank you for sharing such a great article..
Sundaram SubramanianPosted Feb 27, 2018, 12:16 AM
A good kick start for me.. Thanks for sharing the worth content.
Sagar Pandurang KapPosted Feb 27, 2018, 12:11 AM
Helpful & Informative...
Bikash SahuPosted Feb 27, 2018, 12:10 AM
Nice article.thanks for sharing.
Manav PandyaPosted Feb 26, 2018, 11:40 PM
Thanks for sharing such stuff ...
Arun Kumar SinghPosted Feb 26, 2018, 10:52 PM
Good going sir keep it up