FSWD Sem 5
FSWD Sem 5
:
Subject Code IT3501
Published by :
Printer :
ISBN 978-93-5585-395-0
gl7893 55 ls53950 AU 21
9789355853950 [1)
(i)
PREFACE
The importance of Full Stack Web Development is well known in various
engineering fields. Overwhelming response to my books on various subjects
inspired me to write this book. The book is structured to cover the key aspects of
the subject FullStack Web Development.
The book uses plain, lucid language to explain fundamentals of this subject.
The book provides logical method of explaining various complicated concepts and
stepwise methods to explain the important topics. Each chapter is well supported
with necessary ilustrations. practical examples and solved problems. AII the
chapters in the book are arranged in a proper sequence that permits each topic to
build upon earlier studies. All care has been taken to make students comnfortable in
understanding the basic concepts of the subject.
Representative questions have been added at the end of section to help the
students in picking important points from that section.
The book not only covers the entire scope of the subject but explains the
philosophy of the subject. This makes the understanding of this subject more clear
and makes it more interesting. The book will be very useful not only to the students
but also to the subject teachers. The students have to omit nothing and possibly
have to cover nothing more.
I wish to express my profound thanks to all those vho helped in making this
book a reality. Much needed moral support and encouragement is provided on
numerous occasions by my whole family. I wish to thank the Publisher and the
entire team of Technical Publications who have taken immense pain to get this
book in time with quality printing.
Any suggestion for the improvement of the book will be acknowledged and
well appreciated.
Author
Mrs. A. A. Puntambekas
Dedicateò toGod.
(ii)
SYLLABUS
Full Stack Web Development - (1T3501)
UNIT I BASICS OF FULL STACK
Understanding the Basic Web Development Framework - User- Browser - Webserver - Backend
Services - MVCArchitecture - Understanding the differecnt stacks -The role of Express - Angular
-
Node - Mongo DB - React. (Chapter - 1)
UNIT II NODE JS
Basics of Node JS - Installation - Working with Node packages -Using Node package manager -
Creating a simple Node.js application -Using Events-Listeners - Timers- Callbacks - Handling
Data V/O - Implementing HTTP services in Node.js. (Chapter - 2)
UNIT II MONGO DB
Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts -
Access control - Administering databases - Managing collections - Connecting to MongoDB from
Node.js - simple applications. (Chapter - 3)
UNIT V REACT
MERN STACK - Basic React applications - React Components - React State - Express REST
APIs- Modularization and Webpack - Routing with React Router - Server-side rendering.
(Chapter-5)
(iv)
TABLE OF CONTENTS
UNIT I
- 1
Chapter Basics of Full Stack (1 - 1) to (1 - 14)
1.1 Understanding the Basic Web Development Framework... 1-2
1.2 User 1-3
.. 1
1.3 Browser -3
1.4 Web Server 1-5
1.4.1 Apache.. .1 -5
1.4.2 IIS..... .1 -6
1.5 Backend Services. 1-6
....
1.6 MVC Architecture. 1 -7
1.6.1 MVC in Practical... .1-8
1.7 Understanding the Different Stacks. 1-8
1.7.1 Express 1-9
1.7.2 Angular. .1 -9
1.7.3 Node. 1- 10
1.7.4 MongoDB 1-10
- 11
1.7.5 React.... ....1
... 1 - 12
1.8 Two Marks Questions with Answers
UNIT II
2.4.1
2.4.2 Using package.json(Use of npm init). .2 -8
(v)
Node.js Built in Modules.
2.4.3 .2-9
2.5 Creating a Simple Node.js Application 2-11
2.6 Using Events 2- 13
2.6.1 Concept of Event Loop... .2-16
2.7 Listeners 2- 18
2.8 Timers ....2- 21
2.9 Callbacks. 2- 24
2.10 Handling Data I/0 2-25
....
2.10.1 Buffers. 2- 25
....2 - 26
2.10.2 Streams
2.10.3 File System
... 2 -
30
UNIT III
-
Chapter -3 MONGODB (3 - 1) to (3 52)
3.1 Understanding NoSQL and MongoDB. 3-2
3.1.1 NoSQL. 3-2
MongoDB
..... -2
3.1.2 3
3.2 Building MongoDB Environment... 3-4
3.3 User Accounts. 3-13
3.3.1 Listing Users
...3-13
3.3.2 Create User Accounts... .3-14
3.3.3 Remove Users e.. 3-17
(vi)
3.4 Access Control
3- 17
3.4.1 Creating a User Administrator Account
.3-17
3.4.2 Creating Database Administrator Account .3- 19
3.5 Data Types in MongoDB
3-19
3.6 Administering Databases.
3- 20
3.7 Managing Collectíons. 3-22
3.8 Connecting to MongoDB from Node.js 3-29
3.9 Understanding the Objects Used in MongoDB Node.js Driver 3-30
3.10 Simple Applications 3-31
3.11 Advanced MongoDB. 3- 41
3.11.1 Indexing.
.3- 41
3.11.2 Aggregation. 3- 44
4.16.1 Pipes
... 4 -
43
2)
Solved Model Question Paper (M- 1) to (M-
{vi)
UNIT I
Syllabus
Understanding the Basic Web Development Framework User Browser - Webserver - Backend
- -
Services - MVC Architecture Understanding the different stacks - The role of Express Angular
- -
- -
Node Mongo DB React
Contents
1.1 Understanding the Basic Web Development Framework
1.2 User
1.3 Browser
1.4 Web Server
1.5 Backend Services
1.6 MVC Architecture
1.7 Understanding the Different Stacks
1.8 Two Marks Questions with Answers
(1- 1)
Basics of Full Stack
Full Stack Web Development 1-2
Framework
Understanding the Basic Web Development
11|
What is Framework ?
applications which provides a foundation On
Framework is a platform for developing are the
software applications can be built. The front end frameworks soflwarc
which
-
packages that provide
The reusable code modules,
Standardized front end technologies and
and
made interface blocks for making the front end development faster
Ready
simple.
librarjes and
concept :
A web development framework is a collection of tools,
Basic
websites. It provides a basic structure and
technologies that are used to create web applications and
web applications quickly and eficiently.
set of conventions for developers to build
-
some important reason which indicate why do
we use web frameworks
Following are
framework is that it saves timne and enerov
1. Saves time : The most striking feature of web
in developing any app because the developer
doesn't need to worry about session
are taken care of by
handling. error handling and authentication logic. These functions
web frameworks.
app: The web framework itself takes
care of managing directories and
2. Well organized
files. This makes the complete application well organized.
TECHNICAL PUBLICATIONS- an
up-thrust for knowtedge
Full Stack Web Development 1-3 Basics of Full Stack
-
The components of web development framework are as shown below
Backend services
Database
Browser Webserver
MySQL
Request Server-side
Interacts Javascript (XML) Scripts
Oracle
HTML (CSs) CFiles
Response
User
Other
services
1.2 User
User is an important part of web development framework.
Users expectations from a website define the requirements for developing a good
website.
Normally an efficient and easy to use website is preferred by the user. They also expect
that the same website must behave closer to the applications installed on their
computers and mobile devices.
User interacts with the browser by using input devices such as mouse, keyboard on
PC or swipes and taps on mobile devices. The web framework processes the user input
and provides the required visual output.
1.3 Browser.
• Browser is an application for accessing websites. User interacts with the browser in the
web development framework.
The browser plays three roles in web framework -
1. It provides communication to and from the web server.
2. It interprets the data from the server and displays the visual output.
3. The browser handles user interaction through the keyboard, mouse, touchscreen or
other input device and takes the appropriate action.
user. But if
the GET method then the URL string displays the request submitted by the
the POST method is used then URL string does not show the submitted contents.
• Thecommon browsers are Internet Explorer, Mozilla Firefox, Google Chrome, Safari.
1.4.1 Apache
• It is an excellent server because of its two important features: Reliability and
Efficiency.
Secondly it is more' popular because it is an open source software.
That means it is
freely available to anybody. Apache web server is best suitable
for UNIX systems but it
1.4.2 |IS
internet information server
a
The internet information services or is kind of
wcb sCrver
provided by Microsoft. This server is most popular on the Windows platforn.
-
Following are some differences between Apache and lIS servers
Sr. No. Apache web server IIS web server
1
Apache web server is useful on both unix IIS web server is used on windows
based systems and on windows platform. platform.
3 The Apache web server can be controlled For the IIS server, the behaviour is
by editing the configuration file htpd.conf controlled by modifying the window
based management programs called IIS
snap in. We can access
IS snap-in
through the Control-Panel
>Administrative Tools.
Review Question
1. Explain web development
framework with suitable
components of it. block diagram. Also explain the
TECHNICAL
PUBLICATIONS.
an up-thrust
for knowledge
Full Stack Web Development 1
-7 Basics of Full Stack
format with the help of view. This is a script based system using JSP, ASP, PHP and so
on.
3. :
Controller The controller receives input, validates it and then performs business
operations that modify the state of the data model. The controller basically responds to
user requests and performs interaction with the model. Refer Fig. 1.6.I.
II
alerts Controller
updates
about event
model
(IV)
Notifies change
User interacts
View Model
takes model data
and updates view
business logic and UI logic. This makes testing and debugging easy. Modification in one
component does not affect the other.
2. Ability to provide multiple views : In MVC model, we can create multiple views.
3. Faster development process :
MvC supports rapid and parallel development. If an
MVC model is used to develop any particular web application then it is possible that one
programmer can work on the view while the other can work on the controller to create
the business logic of the web application.
tell the waiter your order. The waiter notes down the order and passes it to the chef, in the kitchen.
The chef uses the raw materials from the refrigerator and cooks the dish. The waiter then takes the
dish from the kitchen and then presents it to you, after which you can enjoy your meal.
Here the menu and the food come under the view component.
The waiter acts as a controller.
The chef and the refrigerator can be thought of as the model.
ReviewQuestions
1. Explain MVC architecture with a suitable diagram.
2. Enlist the features of MVCframework.
Database
Webserver
Browser
Angular Node.js
Request MongoDB
Express
Interacts
Javascript JSON
XML webserver
Other
services
1.7.1 Express
Express is used for server side development in full stack. As it is running in Node.js, it is easy
to configure, implement and control the web application.
Following are the reasons why express is a great framework to start from -
1) Routing : Express JS provides a routing mechanism so that it is possible to reach to
different web pages using the URLs.
2) Error handling: Express provides built-in error handling for documents.
3) Easy integration : Express server can easily be implemented behind an existing reverse
proxy system. This allows it to be easily integrated into your existing secured system.
1.7.2 Angular
Angular is a client side framework developed by Google. It is written in TypeScript. angular
provides all the functionalities needed to handle user input in the browser, manipulate data on the
client side. It also controls how elements are displayed in the browser window.
Following are the reasons why angular is agreat framework to start from -
1) Clean : Using angular the developer can develop clean and logical code.
2) Extensibility :
The angular allows to extend almost every aspect of the language to
1.7.3 Node
The Node.js is a development framework that uses Google's
V8 JavaScript engine. The
meaning of V8 JavaScript engine is that it parses and executes the
JavaScript code. The Node.js
code is written in JavaScript and then compiled.
Following are the reasons why Node.js is a great framework to start
from -
1) Easy to use : Node.js is very much easy to set up.
Developing the web applications using
Node.js is also very easy.
2) Extensibility : New modules that are required to extend the Node.js functionality can
be
developed at any time.
3) Event driven scalability : In Node.js, the web requests are processed on the same thread
using a basic event model. Node.js uses a single thread model with event looping.
Similarly the non blocking response of Node.js makes it highly scalable to serve large
number of requests.
:
4) Efficient The Node.js is built on V8 JavaScript engine and it is very fast in code
execution.
5) Use of JavaScript, end-to-end: The one of the important reasons of using Node.js is
that it allows to write both server and client side scripts JavaScript. This makes easier
i
to work for client side developers as well as for server side developers.
1.7.4 MongoDB
MongoDB is a part of backend services, It is basically a scalable NoSQL database. The data is
stored in the form of a JSON object.
Following are the reasons why MongoDB is a great framework to start from -
1) Document orientation : The data is stored in the document form in the MongoDB.
: It is
2) High performance the highest performing database.
3) High scalability: The MongoDB allows horizontal scalability by sharing data across
multiple servers.
4) High availability : MongoDB provides high availability and redundancy with the help of
replication. That mcans it creates multiple copies of the data and sends these copies to a
different server so that if one server fails, then the data is retrieved from another server.
1.7.5 React
ReactJS is an open source, component-based front end JavaScript library maintained by
facebook. This library is responsible only for the view layer of the application. That means this
JavaScript is for building user interfaces.
Following are the reasons why MongoDB is a great framework to start from -
1) Virtual DOM: DOM stands for Document Object Model. It also provides a way to
update the content, structure and style of the document. Virtual DOM is a representation
of the original DOM. When a user updates something on the web application, DOM gets
updated. Updating the DOM is very slow, most of the JavaScript frameworks update the
whole DOM which makes it slower. But actually there is no need to update the whole
DOM, instead, these frameworks should update only the part of DOM that is required to
update. This is what the virtual DOM does. This is why ReactUS's DOM manipulation is
much faster than other frameworks. Due to this property, whenever any change is made
in the web application, then those changes are reflectedon the web page within no time.
2) Components : This feature allows the web developer to create custom elements which
can be reused in HTML.
Review Questions
1. Explain the use of
Nodejs in full stack development.
2. Write short note on - MongoDB.
3. Give the reasons - Why is express useful in web frameworks ?
4. Explain the role of react in web framework.
1. Saves time :
The most striking feature of web framework is that it saves time and energy in
developing any app because the developer doesn't need to worry about
session handling,
error handling and authentication logic.
These functions are taken care of by web
frameworks.
2. Flexibility and customizable :
Add-ons, themes, plugins, widgets enable rapid
customization on the web application. This brings out a lot of flexibility in code
development
Q.3 What are the components of web development framework
?
Ans. The components of web development framework are -
:
(1) User (2) Browser (3) Web Server (4) Backend services
Q.4 Give the importance of browser
: -
Ans. The browser plays three roles in web framework
1. It provides communication to and from the web server.
2. It interprets the data from the server and displays the visual output.
3. The browser handles user interaction through the keyboard, mouse,
touchscreen or other
input device and takes the appropriate action.
Ans.:
i) GET:The GET request is typically used to retrieve data from the server. This data can be in
Ans. :
1) Backend services are the services that run behind the web server. These services provide the
data to thé web server which is requested by the web browser.
2) The most commonly used backend service is a database that stores the information.
Q.9 What is MVC?
:
Ans.
1. Model : This part of the architecture is responsible for managing the application data. This
module responds to the request made from view. The model gives instructions to the
Q.10 stack ?
VWhat is full
anv weh
:
Full stack development is development of both front cnd and back cnd of
Ans.
application.
2. Express 3. AngularJS 4. Nodc.js 5. Rcact.js
The full stack consists of
-1. MongoDB
2 NODE JS
Syllabus
Basics of Node JS - Installation Working with Node packages Using Node package manager -
- -
Creating a sinple Node.js application Using Events Listeners - Timers - Callbacks - Handling
-
-
Contents
2.1 Basics of Node JS
2.2 Installation
2.3 Working with Node Packages
(2- 1)
Full Stack Web Development 2-2 NODE JS
Uses of Node.js
It can perform various tasks such as -
1) tcan create, open, read, delete, write and close files on the server.
2) It carn collect form data.
3) It can also add, delete, modify data in databases.
4) It generate dynamic web pages.
Features
Following are some remarkable features of node.js -
Review Question
1. What is Node js ? Enlist thefeatures ofNodejs.
2.2 Installation
• For executing the Nodejs scripts we need to install it. We can get it downloaded from
htps:/nodejs.org en.
The installation can be done on Linux or Windows OS. It has very simple installation
procedure.
nde
HOME ABOUT DOWLOADS DOCs GET
INOKD SriSTTY
MBlacktivesMatter
New security releases now available for 15.x, 14.x, 12.x and 10.x
release lines
Download
Download node MSI for windows by clicking on 14.16.0 LTS or 15.l1.0 Current
button.
• After you download the MSI, double-click on it to start the installation as shown below.
Nodejs Setup
Command Prompt X
D:\>node -v
14.15.4
D:\>
If the node.js is successfully installed. then some version number of the node.js which
you have installed in your PC will be displayed.
After successful installation we can now execute the Node.js document. The Node.js file
has extension js.
Following is a simple node.js program which can be written in notepad.
app.js
console.log("Weicometo first Node.js Application program");
Output
C Command Prompt
þ:\>node app.js
elcome to first Node.js Application program
p:\
C CAWindows\ System32\cmd.exe
D:\NodeJSExamples>npm version
5.14.10
b:\NodeJSExamples>
There are various command line options that npm uses. These options are as follows -
Option Purpose Example
install Installs the
packages either using a npm install express.
package.json or from the repository or from
a local location.
npm install.
Owner Manages the ownership of published npm owner add <user> <package-spec
packages.
npm owner rm <user> <package-spec>
Is :
List all the users who have access to
npm owner ls <package-spec>
modify a package and push new versions.
Handy when you need to know who to bug
for heip.
D:
\odeJSExamples>npm express +
install as Issue this command
a
D nôtlée created
HARN
lockfile
No
package -lock.json. You should comit this file.
Lti mypackageg1.0.1 repository field.
[email protected]
added 50 packages from 37 contributors and sudited 50 packages in 4.969s
found 0
vulnerabilities
D:\ModeJSExamples>,
As soon as we issue this command the package-lock file gets generated in the current
folder.
For using this module in our program we have to use following command -
var ex = require('express');
Example of using the existing module
Step 1: We will install the module upper-case by issuing the install command
G CAWindows\System32\cmd.exe X
D: \NodeSExamples>npa
install upper-case
npn WARN nypackageg1.0.1 No repository field.
[email protected]
ladded 2 packages from 2 contributors and audited 52 packages in 4.047s
found e vulnerabilities
D:\NodeJSExamples>
suitable text editor and write node js script that makes use of this module.
moduleDemo.js
var upp ch require(upper-case);
console.log(upp ch.upperCase(iam proud of you"):
Output
CAWindows\ System32\cmd.exe X
D:\NodeJSExamples>node noduleDemo.js
I AM PROUD OF YOU
D:\NodeJSExamples>
Step 1: Create a sample folder. Open command prompt and go to that directory location. For
instance -I have created a folder named nodejsexamples. Issue the command npm init at the
command promp.
D:WlodeJSExenples>npn init
This utility will walk you through creating a package.json file.
7t only covers the most conon items, and tries to guess sensible defaults.
See np help init for definitive documentat ion on these fields
end exactly that they do.
Usenpn install <pk» efterwards to install a package and
sve it as a dependency in the package.json file.
"name": "mypackage",
"version": "1.0.1",
"description" : "This is my
first package!!!",
"main": "callbackDemo.js",
"scripts": {
:
"test" "runpackage"
"author": "A.A. Puntambekar",
"license": "ISC"
p:\NodeJSExamples>
Once you execute the above commands, the package.json gets created. You can open
and test it using a simple notepad.
Step 1: Open Notepad and create a js file as follows. I have created an application using the
name app.js. Here is the code.
app.js
var assert = require('assert');
assert(10< 2);
CIWndows\Systen32\nd eve
a
AssertionError (ERR ASSERTION]: The expression evaluated to falsy valve:
assert(1e 2)
Note that as the 10 is not less than 2, the above code will raise the error namcd
AssertionError.
(2) cluster
The cluster module helps in creating a child process. Both the main and child processes
can run simultaneously and share the same server port. Let us see its use with the help of
a
demo example.
Step Open Notepad and create a js file as follows.
1 : I have created an application using the
name app.js. Here is the code.
app.js
var cluster = require(chuster');
Y (cluster.isWorker) {
Console.log(Child Process);
}else {
console.log('Main Process');
cluster.fork():
cluster.fork();
chuster.fork():
Step 2: Now, open the command prompt and issue the command.
node appjs
Please refer following screenshot
EHode)SExamples\modules>node app.js
Main Process
Child Process
Child Process
Child Process
The os module provides information about the operating system of your computer.
Step 1: Open Notepad and create a js file as follows. I
have created an application using the
name app.js. Here is the code.
app.js
var os = require('os');
console.log("Platform on My Computer:" + os.platform():
console.log("Architecture of My Computer:" + os.arch()):
Step 2 : Now, open the command prompt and issue the command
node app.js
Plcase refer following screenshot
CAWindows\System32\Cmdexe
E:\NodeJSExamples\modules>node app.js
Platform onMy Computer: win32
console1.js
var emp name 'Ankita,
emp depts = {
dept1: 'Sales', dept2: 'Accounts'
Output
oL Command Prompt
D: \ModeJSExamples>node
consolel.js
Name: Ankita
Departments: "depti":"Sales,"dept2":"Accounts"}
D: \Node3SExarples
Output
Name: Ankita
Departments: ('dept1"Sales, dept2 Accounts")
3) console.error (|dáta]|, ..) : This method prints to stderr
with newline
console3.js
var code = 401
Console.error(Error!! code)
Output
Error!!! 401
console4.js
var fs = require(fs'):
fs.open("input.dat",T,function(er,fs){
if(err)
console.warn(e);
else
console.log("File opening successful!!!");
Output
CCommand Prompt
D: \WodeJSExamples>node console4, js
[Error: ENOENT: no such file or direcory, open 'D: MlodeiSExamples\input.at'] {
errno: -4058,
code: ENOENT
syscall: 'open
path: "D:\\Mode1SExamples\\inpüt dat
D:\NodeJSExamples>
Review Question
Explain amy
four methods of console object in nodejs with suitable examples.
2.6 Using Events
• Event-driven programming is a programming paradigm in which the flow of the
program is determined by events such as user actions (mouse clicks, key presses). sensor
outputs, or messages from other programs/threads.
Event
loop
What is an Event ?
Every time when a user interacts with the webpage, an event occurs when the user clicks
the mouse button or presses some key on the keyboard.
When events are triggered, some functions associated with these events get executed.
Event driven programming makes use of the following concepts -
i) When some events occur, an event handler function is called. This is basically a call
back function.
ii) The nain program listens to every event getting triggered and calls the associated
event handler for that event.
once(event, listener) Adds a one-time listener for the event. This listener is invoked
only the next time the event is fired, after which it is removed.
emit(event, [argl]. [arg2]. [...]) Raise the specified events with the supplied arguments.
eventDemo1.js
/ get the reference of EventEmítter class of events module
var events = require(events');
1/ Raising FirstEvent
em.emit(FirstEvent');
Output
DANodeJSExamples>node eventDeno1.js
When event occurs, My Function is called.
Program Explanation :
In above program,
1) We have to import the 'events' module.
2) Then we create an object of the EventEmitter class.
3) For specifying the event handler function, we need to use the on) function.
4) The on) function requires two parameters - Name of the event to be handled and the
callback function which is called when an event is raised.
5) The emit() function raises the specified event.
eventDemo1.js
the reference of EventEmitter class of events module
Lget
var events = require(events);
lcreate an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
var myfunction = function(data1,data2) {
console.log("When event occrs, My Function is called');
console.log("Data passed is: "+data1+" "+data2):
Output
DINodeJSExamples>node eventDemo 1.js
When event occurs, My Function i called
Data passed is: data1 data2
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development 2- 16 NODE
Blocking
myapp.js Calistack Event Queue
operations
Event loop)
Task1 Taskn Execute callback
The Event Loop is a main loop running continuously for executing the callback
functions. When an async function executes, the callback function is pushed into the
queue. The JavaScript engine doesn't start processing the event loop until the code after
an async function has executed.
Example Code
console.log(Task1");
console.log(Task2'):
setTimeout(function() {console.log(Task3") }.1000);
console.log("Taks4");
Output
Ga Command Prompt X
D:\Node)SExamples>node EventLoopDemo.js
Task1
Task2
Taks4
Task3
D:\NodeJSExamples>
Pending
Callbacks
Idle,
Timers Prepare
Close Poll
Callback
Check
Fig. 2.6.3
2.7 Listeners
An event listener is a technique or a function that waits for an event to occur. The
listener is programmed to react to an input or signal by calling the event's handler.
The event module allows us to create and handle custom events in Node.js.
The EventEmitter class is used to raise and handle the events.
Following are some commonly used properties and methods that implements the event
listeners.
Method Purpose
addListener(event, listener) Adds a listener to the end of the listeners array for the
specified event. No checks are made to see if the listerier has
already been added.
removelListener(event, listener) Removes a listener from the listener array for the specified
event. Caution :Changes array indices in the listener array
behind the listener.
prependOnceListener(event, Iistener) It will add the one-time listener to the beginning of the
array.
Example Code
var events = require('events');
var eventEmitter = new events.EventEmitter();
I/Event listener #1
var listener1 = function listener 1() {
console.log('Event listener#1 executed.'):
I/ Event listener #2
var listener2 = function listener2() {
console.log('Event listener#2 executed.');
I/Event listener #3
var listener3 = function listener3() {
console.log('Event istener#3 executed.):
eventEmitter.on('myevent', listener2);
eventEmitter.on('myevent, listener3);
Output
Event listener#1 executed.
Event listener#2 executed.
Event listener#3 executed.
Number of Eventlisteners are: 3
Following are the events in the queue...
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
Full Stack Web Development 2
-21 NODE JS
2.8 Timers
Timers module in Node js provides a way for scheduling the functions to be executed
on some given timc.
For using the timers module in Node.js it is not required to import it via require)
function as all the methods are globally available to JavaScript API. Hence we do not
have to use “require" in the source code while using timer functions.
There are three set timer functions used in Node.js
1.setTimeout() 2. setImmediate() 3. setlnterval()
-
Let us understand them with suitable examples
1) setTimeout() :
This function is used to set one time callback after delaying by some
milliseconds.
Syntax
setTimeout(function,delay in milliseconds)
Timer1.js
console.log("Task1");
setTimeout(function() {console.log("Taks2:Executing After 4 seconds") }4000);
console.log("Task3");
Output
CN Command Prompt X
D:\NodeJSExamples>node Timer1.js
Task1
Task3
Taks2:Executing After 4 seconds
D:\Node]SExamples>
Timer2.js
console.log('Greeting message will be displayed soon..");
var myfun = (user) =>{
console log('Good Morning "+user);
Output
Command Prompt X
b:\WodeJSExamples>node timer2.js
Greeting message will be displayed soon...
Good Morning Ankita
D:\NodeJSExamples>
We don't need to pass any time interval to this method. The first argument is the function
to execute. We can also pass any extraarguments to this function.
This method will execute a function right after the next code block which is present afte
TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Full Stack Web Development 2- 23 NODE JS
Output
Comand Prompt
3) setInterval) This function helps to execute a task in a loop after some time interval.
:
Output
Command Prompt
p:\Wode)SExamples>node timer3. js
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
D:\ModeJSExamples>
The above code present inthe function myfun gels executed after every 1000 millisccond.
To break this program nunning in a loop we have to press controlte.
2.9 Callbacks
What is callbacks ?
Callbacks is a function which is usually passed as an argument to another function and u
console.log('Serving User2"):
console.log"Serving User3');
console log(Good Bye!l!");
Output
D
NodeJSExAnples>node callbackDemo.js
Serving User1
Serving User2
Serving User3
Good Byel!!
Program Explanation :
In above program.
) We have to read a file named myfile.trt. but while reading a file it should not block the
Cxccution of other statements. hence a call back function is called in which the file is
read.
2) By the time file gets read, the remaining two console functions indicating "Serving user
T" and "Serving user 2" are not blocked. rather they are executed, once the contents are
read in the buffer, then those contents of the file are displayed on the console.
Review Question
1. Explain the callbacks in node js wih suitable example.
Writing to Buffer
write(stringl,offset]. l.length||,encodingl)
Example Code
Following is a simple node js program that shows how towrite data to the buffer.
BufferExample.js
var buffer = new Buffer(50):
buffer.write(Good Morning ):
console.log (buffer.toString(utt8):
Output
GoodMoming
Program Explanation : In above program,
We have used write method for writing to the buffer. For displaying the string written to
the buffer we have to use toString method along with the encoding scheme.
Reading from Buffer
Example Code
var buffer = nevw Buffer(50);
buffer.write(Good Morning');
console.log(buffer.toStringutfB);
2.10.2 Streams
Stream can be defined as objects that reads data from source or writes the data to
destination in continuous fashion.
The stream is an EventEmitter instance that emits several events. Following are the events
that occur during stream operations -
1) data : This event is fired when we want to read the data from the file.
2) end :
When there is no more data to read then this event is fired.
3) error : If any error occurs during reading or writing data then this event is fired.
4) finish :
When data is completely flushed out then this event occurs.
There four types of streams,
1) Readable : This stream is used for read operation only.
2) Writable : This stream is used for write operation only.
:
3) Duplex This type of stream is used for both read and write operation.
4) Transform : In this type of stream the output is computed using input.
Write Operation
The steps that are followed to write data to the stream using node.js are as follows -
Step 1: Import the file stream module fs using require.
Step 2: Create å writable stream using the method createWriteStream.
Step 3 : Write data to the stream using write method.
Step 4: Handle the events such as finish or error(if any)
Following Nodejs script shows how to write data to the string,
writeStreamExample.js
var fs = require("fs");
var str ="This line is written to myfile"
var ws = fs.createWriteStream('sample.txt');
ws.write(str utf8);
ws.end();
Console.log("The data is written to the file..."):
G Command Prompt
D:\NodeJSExamples>node writeStreamExample.js
The data is written to the file...
D:\NodeJSExamples>type sample.txt
This line is written to myfile .
D; \NodeJSExamples>
ws.on(error, function(err) {
console.log(err.stack);
D:
Read Operation
For reading from the stream we use createReadStream. Then using the
data event the data
can be read in chunks.
Example Code
var fs = require("fs);
var str =
var rs = fs.createReadStream('sample.txt');
TS.setEncoding("utf8"):
TECHNICAL. PUBLICATIONS-
an up-thrust forknowledge
Full Stack Web Development NODE JS
2- 29
//handling stream event 'end'
rs.on('end'.function(){
console.log(str)
Sample.txt
This line is written to myfile
Output
G Command Prompt X
D:\NodeJSExamples>node readStreamExample.js
This line is written to myfile
D: \NodeJSExamples>
Pipe Operation
The pipe operation is a kind of operation in which output of one stream acts as an input of
another stream.
There is no limit on pipe operation that means, all the output of one stream can be fed as
input to input to another stream.
Following are the steps used for using the pipe operation in your node.js program -
pipeExample.js
var
fs require('fs");
var rs fs.createReadStream(input,.txt');
rs.setEncoding(utf8"):
var ws = fs.createWriteStream('output.txt);
rs.setEncoding(utf8");
rs.pipe(ws):
console.log("Data is transfered from 'input.txt' to 'output.txt):
Output
A Command Prompt
1. Read Operation
The read file operation can be performed synchronously or asynchronously.
For reading the file synchronously we use readFileSync method. And for reading the 1
function(err, data)
I/function body
Example code
var fs = require("fs"');
fs.readFile('input.txt', function(ert,data){
if(err)
console.log(err);
console.log(data.toString());
input.txt
Hello friends,
Node.js is really amnazing.
Really enjoying it.
Output
Gs Command Prompt
D:\NodeJSExamples>node readFileExample.js
Hello friends,
Node.js is really amazing.
Really enjoying it.
D:\NodeJSExamples>
readFileExample.js
var fs require(fs");
var data = fs.readFileSync(input.txt):
console.log(data.toString():
Syntax
Lopen(path, flags|,mode),callback)
The appendFile) method is used to write the contents at the end of the specified file.
Example Code
var fs = require(fs");
str = "This line is written to the file":
fs.appendFile(myfle.txt, str,function{er){
if(err)
console.log (err)
console.log(File appended!!!');
Output
Command Prompt
X
D:\NodeJSExamples>node appendFileExample.js
File appended!!!.
D:\NodeJSExamples>type myfile.txt
This line is written to the file
D:\Node]SExamples>
TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
Full Stack Web Development
2-33 NODE JS
Example Code
var fs = require("fs");
str = "This line is replacing the previous contents";
fs.writeFile('myfile.txt, str,function(er){
if(err)
console.log(err)
console.log(File Writing Done!!);
});
Output
cN Command Prompt X
p:\NodeJSExamples>node writeFileExample.js
File Writing Done!!!
D:\NodeJSExamples>type myfile.txt
This line is replacing the previous contents
|D:\NodeJSExamples>
Syntax
unlink(path, callback)
where
path: Is a path of the file to be deleted.
callback :It is a callback function with the only one argument for 'error'.
Example Code
var fs = require("fs")};
fs.unlink('myfile.txt',function(err){
if(err)
throw err;
console.log("File is deleted!!!");
});
C Command Prompt
D:\NodeJSExamples>node deleteFileExample.js
Deleting a file
File is deleted!!!
D:\NodeJSExamples>type myfile.txt
The system cannot find the file specified. Checking if file gets deleted or not.
D:\NodeJSExamples>node deletefFileExample.js
D:\NodeJSExamples\deleteFileExample.js:4
throw err; Again trying to delete a deleted
file, hence exception is thrown.
ENOENT: no such
[Error: file or directory, unlink 'D:\NodeJSExamples\myfile.txt'] {
errno: [33m-4058+[39m,
code: +[32m'ENOENT'+[39m,
syscall: +[32m'unlink'+[39m,
path: +[32m'D:\ \NodeJSExamples\ \myfile.txt'+[39m
D:\NodeJSExamples>
Review Question
1. With necessary source code, explain how to use file I/O operations in node.js.
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 2-35 NODE JS
Protocol Subdomain Hostname Port nunber Pathname Query string Query string Hash
separator
1) Protocol : This is the request protocol used by the client while making the request. The
popular protocols in web-based applications are http and https which display the page
in HyperText(HTML) format. Some other protocols are - FTP i.e. file transfer protocol
which is used for file transfer, SMTP i.e. Single Mail Transfer Protocol which is used
for sending emails.
2) Subdomain : It is a specific type of resource to be delivered to the client. The
subdomain www is a general symbol for any resource on the web.
3) Hostname : The host name identifies the host that holds the resource.
4) Port number : A port number specifies the type of service that is requested by the
client, since servers often deliver multiple services. Some default port numbers includes
80 for HTTP and443 for HTTPS servers.
5) Pathname It specifies the exact location of the web page, file or any resource that the
:
where,
Example Code
const querystr= require'querystring");
var str = "User=admin&password=pass1234";
Output
PS E:\NodeJSExamples\QueryStringDemo>
node app.js
Parsed Object: [Object: null prototype] {User: 'admin', password:
pass1234}
2.11.3 Request, Response and Server Object
The web module is mainly controlled by a web server
that handles the requests and
provides the responses. These requests and responses are handled
by HTTP(Hyper Text
Transfer Protocol) protocol.
The user submits the request using a web browser. Thus the communication between web
server and web browser is handled
by HTTP protocol. Following steps. explain this
communication
When a user submits a request for a web page, he/she is actually
demanding for a page
present on the web server.
When a web browser submits the request for a web page,
the web server responds to thS
request by sending back the requested page to the web browser
of the client's machine.
Request for
web page
Web browser Serves the Web server
web page
Step 2 Theweb server locates the desired web page on the website and responds by
:
sending
back the requested page. If the page doesn't exist, it will send back the
appropriate error page.
Step 3: The web browser receives the page and renders it as required.
The request and response objects of the HTTP module in Node.js are the important
objects of client server communication.
Following are important objects that we will learn in this section -
Syntax
http.request(options,callback)
Parameters
1) options parameter is an object which is responsible for defining how to open and send
the client HTTP request to the server. Various options that can be specified while
creating ClientRequest are as follows -
Property Purpose
host The domain name or IP address of the server to which the request is
made. Default is localhost.
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development 2- 38
NODE
JS
callback parameter is callback function which is called after the request is sent
a
2)
tothe
server. Then this function handles the response obtained fromthe server(note
hat itisa
callback function).
Example Code
var http= require(http");
var server = http.createServer(function(request,response) {
I/Creating a response
response.writeHead(200.(Content-Type": text/plain'"});
response.end("Hello, This text is displayed as a response to the clhent request!!");
zeq.end(0:
Output
Open the terminal window or command prompt and get the output on the console
follows -
Now open some suitable web browser such as Mozilla Firefox or Google Chrome
and typc the localhost:8082 as URL. It is illustrated by following screenshot
localhost.8082 +
C O localhost:8082
Other bookmarks
getHeader() This method is to get the value of an HTTP header that has been set in the
response.
setTimeout() Sets the timeout value of the socket to the specified number of milliseconds.
close This property is uscd to when to the conncction to the client is closedIprior
to the response.end) method.
end() This method is an indication for the server that the response is now
complete.
Example Code
Node.js has a built-in module named http which allows us to transfer data over the Hper
Text Transfer Protocol(HTTP).We will build a web server using http module.
WebModuleExample.js
var http= require('http);
var server = http.createServer(function(request,response) {
response.writeHead(200,("Content-Type": "text/plain"});
response.end(Welcome to this Web Module Application!"):
server.listen(8082);
console.log("Server is running on port 8082 port...");
Output
Step 1: First of all open the command prompt and type the following command.
D:\NodeJSExamples\HttpApp>node WebModuleExample.js
Server is running on port 8082 port...
Step 2 :Now open some suitable web browser such as Mozilla Firefox or Google Chrome an0
type the localhost:8082 as URL. It is illustrated by following screenshot
localhast.8092
O localhost:A082
: In
Seript Explanation above given Node js seript.
1) We have imported http module.
2) The http.createServer) method includes request and response parameters which is
supplied by Node.js.
a response, first it sets the response header using the writeHead) method and
3) Tosend
then writes a string as a response body using the write() method.
4) Finally, Node.js web server sends the response using end) method. But we can directly
write the response body using the end method.
5) Using the server.listen method we can specify the port number on which our web
server is running.
6) Just refer to the illustrative output given above.
WebModuleExample.js
var http= require("http");
var server = http.createServer(function(request,response) {
if(request.url == "/"){
Iesponse.writeHead(200, ("Content-Type": "text/html"} );
response.write("<html><body ><h1>Welcome to this Web Module
Application! </h1></body></html>");
response.end():
else
response.end("This is invalid request");
server.listen(8082);
console.log("Server is running on port 8082 port.);
Output
|:\NodeJSExamples\HttpApp>node WebModuleExample.js
on .
Server is running port 8082 port..
We can open a web browser and get the about page by making the request using the URL
as "localhost:8082/Abou". The illustrative output is as given below -
X
localthost£032/About
f C 0 localhost:B082/About
About Page
Trailers This is an object containing any trailer headers sent with the
request/response.
Method It specifies the methods for request and response. The method can be GET,
POST,CONNECT.
statusCode Itspecifies the three digit status code from the server.
socket This a handle to the net.socket object used to communicate with the client
and server.
url The url string is sent to the server. This string can be parsed using url.parse)
Example Code
const http = require(http);
I/ Sending a response
res.writeHead(200, {'Content-Type: text/plain });
res.end(Welcome');
server.listen(8082, () =>{
console.log('Server is listening on port 8082'):
Request URL: /
Request method: GET
Request URL: /favicon.ico
Open the web browser and issue the address "localhost:8082", the response on the weh
page is displayed.
S localhost:8082
O localhost:8082
Other bookmarks
ielcoe
3) Then using the reqparameter we have read the method and url properties.
4) Similarly we can send the response to the client using WriteHead) and end) methou
of the http.SeverResponse. object which is passed as a res parameter to the requ
handler function.
5) Thus http.IncomingMessage takes part in both client request and server response.
The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client. The createServer() method is used to create an HTTP server. This
method returns the server object. Once the server object is created then begin listening on it
by calling the listen() method on the server object.
For example -
app.js
var http =require("http");
var server = http.createServer(function(request,response) {
response.writeHead(200,("Content-Type": "text/plain"} ):
response.end("Welcome to this Web Module Application!!!"):
server.listen(8082);
console.log("Server is running on port 8082 port...");
Review Questions
Explain the concept of query string and formparameters.
2. Explain the htp.clientRequest object in Nodejs with suitable examples.
3. What are the properties and methods of http.ServerResponse ?
For example -
var emp name = Ankita.
emp depts =
dept1: Sales, dept2: 'Accounts
Example Code
console.log(Task1;
serTimeout(function) {console.logTake2:Executing
Consolelg(Tark3');
After 4 seconds") },4000);
TECHNICAL PUBLICATIONS-
an up-thrust for
knowledgo
NODE JS
Full Stack Web Development 2- 47
Q.9 How callback functions are handled in Node.js ?
Ans. :
Callbacks is a function which is usually passed as an argument to another function and it
is usually invoked after somc kind of event.
var fs = require("s'):
console.log('Serving User 1")
fs.readFile('myfile.txt', function (err, data) (
|if (err) return console.error(err):
Console.log("*** Contents of the File are..***"):
console.log(data.toString());
console.log("Serving User2");
console.log("Serving User3"):
console.log("Good Bye!!"):
Q.10 What is pipe operation in Node.js.
Ans. :
The pipe operation is a which output of one stream acts as an input
kind of operation in
a
website's database. Each query string is made up of a parameter and value joined by the
are joined using the ampersand
equals (F) sign. In case of multiple parameters, query strings
or any other form of data on
(&) sign. The parameter can be a number, string, encrypted value
the database.
Q.12 Explain the use of ClientRequest object.
server.
Ans. : The ClientRequest object is used to monitor and handle the response from the
For implementing the ClientRequest object the call to the http.request) is made. The syntax
-
to this method is as follows
http.request(options,callback)
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
UNIT III
3
Syllabus
MONGO DB
Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts - Access
control - Administering databases - Managing collections Connecting to MongoDB from Nodejs
-
simple applications.
Contents
3.1 Understanding No SQL and MongoDB
3.2 Building MongoDB Environment
3.3 User Accounts
3.4 Access Control
3.5 Data Types in MongoDB
3.6 Administering Databases
3.7 Managing Colections
3.8 Connecting to MongoDB from Node,js
3.9 Understanding the Objects Used in MongoDB Node,js Driver
3.10 Simple Applicaions
3.11 Advanced MongoDB
3.12 Two Marks Questions with Answers
(3- 1)
MONGO
3-2 DB
Full Stack Web Development
Need:
adopted for following reasons
The NoSQL database technology is usually
as a part of fundamental
1) The NoSQL databases are often used for handling big data
architecture.
structured, semi-structured
2) The NoSQL databases are used for storing and modelling
and unstructured data.
3) For the efficient execution of database with high availability, NoSQL is used.
so it scales out better than relational
4) The NoSQL database is non-relational,
databases and these can be designed with web applications.
5) For easy scalability, the NoSQL is used.
Features:
1)The NoSQL does not follow any relational model.
2) It is either schema free or have relaxed schema. That means it does not requius
3.1.2 MongoDB
MongoDB is an open source, document based database. known as
noow
It is
developed and supported by a company named 10gen which is
MongoDB Inc.
The first ready version of MongoDB was released in March 2010.
TECHNICAL PUBLICATIONSan
up-thrust forknowledge
Full Stack Web Development MONGO DB
3-3
Why MongoDB is needed ?
There are so many efficient RDBMS products available in the market, then why do we
need MongoDB ? Well, all the modern applications require Big data, faster development and
flexible deployment. This need is satisfied by the document based database like MongoDB.
Features of MongoDB
1) It is a schema-less, document based database system.
2) It provides high performance data persistence.
3) It supports multiple storageengines.
4) It has a rich query language support.
5) MongoDBprovides high availability and redundancy with the help of replication.
That means it creates multiple copies of the data and sends these copies to a different
server so that if oneserver fails, then the data is retrieved from another server.
6) MongoDB provides horizontal scalability with the help of sharding. Sharding
means to distribute data on multiple servers.
Databases Databases
Tables Collections
Rows Documents
Columns Fields
Fig. 3.1.1
Consider a
"
id':527191e810c19349de860eg,
"Name":"'Ankita",
"Course":"Computer Engineering",
"Address":{ Document 1
"line1":"ILane1"
"line2" Lane2"
}
" id":557f191e810c19729de860ea,
Name Course AddressLine1 AddressLine2 "Name":"Prajkta",
"Course""'Mechanical Engineering",
Computer Lane1 Lane2
Ankita "Address":{ Document 2
Engineering
"line1":"Street1",
Mechanical "line2:"Street2"
Prajkta Street1 Street2
Engineering
Civil
Kavita Engineering Road1 Road2
id:507f141e510c19729dey60ed,
"Name":"Kavita",
Fields "Course""Civl Engineering',
+"Address":{ Document 3
"line1"Road1",
"line2":"Road2"
Fig. 3.1.2
Review Questions
1. What is NoSQL ? What is the need for it ? Enlist various feature of
NoSQL.
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development MONGO DB
3-5
Open File - Security Warning X
Run Cancet
While files from the Internet can be useful, this file type can
potentially harm your computer. Only run software from
publishers you trust. What'sthe risk?
Just click on Next button and choose the Complete option for installation. Follow the
normal procedure of installation by clicking the Next button. If you do not want to install the
MongoDB Compass(the Graphical tool of MongolDB), then simply uncheck the option.
Finally you will get following window on successful installation.
Cancel
Euck Anish
tcmalloc
If the
MongoDB is
correctly
installed
"environnent": {
then you
"distmod": "indows" will get this
"distarch": "x86 64" result
"target_arch"x86_64"
C:\Progran Files\MongoDB\Server\6.9\bin>
Environment
To set the environment variable, Open System Properties and click on
Variables
Gytem Dropertis
Setings
User Profles
Desktop setings related to your sign-in
Setfings
Setngs
EnvironmentVariables
OK Cancel pply
Envircnment Varabtes
Varnable Value
ChocolateylastPathUpdate 13255015184767214
classpath C\Program FilesJava\ydk-150.1\bn\mysqi-connector-java-5.
OneDrive C\Users\DELL\OneDrve
OneDriveConsumer CAUsers\DELL\OneDrve
Path CAUsers\DELL\AppData\Loca/\ Micccsoft\WindowsAppsCUs
TEMP C\Users\DELL\AppData\LocalTemp
TMP C\Users\DELL\AppData\ Loca\Temo
System variables
Variable Value
Chocolateytnstal! C\ProgramData\chocolatey
classpath CAProgram FilesJava\yak-150.1\oin\mysqt-connector-java-5.
ComSpec C\Windows\system32\cnd.exe
DriverData CWindows| System32\Drvers\DrrverData
JAVA HOME C\Program Files\Javalydk-15.0.1
NUMBER_OF_PROCESSORS 8
OS Windows_NT
OK Cancel
Then click on the path variable and set the path of MongoDB by clicking New button.
Edit environment variable
CProgram Fites\MongoDE\Server60\bin
Delete
Move Up
Move Down
Edit text..
OK Cancel
Then simply continue clicking ok button and just come out of the environment variable
window.
Installing Mongo Shell
For working in MongoDB sheli, the shell is separately installed. For installing it, go to the
on Download button. The
website https://www.mongodb.com/try/download/shell. Click
zip
file gets installed. Just unzip this file to get the MongoDB shell installed. Then set
the
environment variable to set the path for MongoDB shel. In my case, the mongosh.exe Is
C:MongoDBSh\mongosh-1.8.0-win32-x64\mongosh-1.8.0-win32-x64\bin,
present at the path
hence I willadd the New path in the Environment variable tab as "CAMongoDBShmongos
1.8.0-win32-x64\mongosh-1.8.0-win32-x64\bin"
Move Up
Move Don
Edit text
OK Cancel
To verify the installation, open the command prompt and issue the command mongosh.
-
The test prompt will appear as follows
Amongosh mongodb://n27.00. X X
2023-04-20T16:39:36. 203+05:30: Access control is not enabled for the database. Read and write ac
cess to data and confiquration is unrestricted
Enable MongoDB's free cloud-based monitoring service, uhich will then receive and display
metrics about your deploynent (disk utilization, CPU, operation statistics, etc).
The nonitoring data will be available on a MongoD8 website with a unique URL
accessible to you
and anyone you share the URL with. MongoD8 may use this information to nake product
inprovements and to suggest MongoDB products and deplaynent options ta vou.
To enable free monitoring, run the following comnand: db.enableFreeManitoring ()
To peroanently disable this reminder, run the following command: db.disableFreeHonitoring ()
test>
Solutions Docs
Prcng Leam
mongoDB. Cioud Softwe
Communitly Sever
open documrt databace
A fro and
Enterprise Sever
Rovanced fastues tend Secuty
Developer Tools
MongoD8
Ccrnect conhgure src work with
CompasS
MIngoDE
Ops Manager
Or-prem nageet platarn ior Morg08
MongoDE Canectors
Ees egans to you duta state
MengoDB ot pd
ofers the fierible docunent moce zlong with ad hoc queries, indexi
a operating
Select any suitable version as per your operating system. As mine is Windows
system of 64 bit, I have chosen following option.
Available Downloads
Veron
1.260 (Stable)
Paiorm
Windows 64-bit (7+) (MS)
Pakaze
Documeritaton
Archrved reieases
TECHNICAL PUBLICATIONS.
an up-thrust for
knowledge
Full Stack Web Development MONGO DB
3- 11
Click on the Download button. The exe file will get downloaded. Double click the installer
file which is downloaded in your PC and the installation process for Mongo DB Compass will
start.
MongoDB Compass Setup X
Simply go on clicking Next button and then click on the install button on the subsequent
window. Finally you willget the installation completion screen.
Windows, locate
Just click Finish button. Now, click the Start button
of
MongobB
Compass Application and simply click it to start the GUI for Mongo DB. You
will ge
following GUI
•MonoE Compas -Connect
NeConrecon
Fvorites New Connection RRE
F in connection fields indhvidualy
Recens
Paste your connection string (SRV or New to Compass end dont have a cluster?
Standard 0) tyou don) alteady have a chster, vou can
create ons far free using MongoB Atlas.
e.g mongorb +<dhsemae Dastwordéchs
CREATE FREE CLUSTER
Conect
How do I find my connection string In
Atias?
!yx hve an Atlas custot, go 1othe
Cluster
Vew Cck the Connect button for the cluster
to wtch you wsh to connect.
Spe cxage
SegaToe
CREAIEDRRSE
FAVORTE
localhost:27017
CUUSTER adrmin 20.0K8
Standalone
config 24.0KB 2
MangoDB444 Communty
koca! 20.0KB
admn
Sconfig
onsinetB
mongosh mongodb://127.0.0. X X
admin>
admin>
.
TECHNICAL PUBLICATIONS an up-thrust for knowiedge
Full Stack Web Development 3- 14 MONGO DB
mongosh mongodb://127.0.0. X X
admin> cursor.count)
admin>
roles The roles granted to the user. Can specify an empty array array
I] io create users without roles.
mongosh mongodb://127.0.C X
Now to test, if the user named Parth is created or not, we issue the show users command
at the MongoDB shell.
X
l mongosh mongodb://127.0.0.
test>
The above user is created without any role. But we can assign the role to the user during
the createUser command.
readWrite This role provides all the privileges of the read role plus the
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the database
as well as clean, modify, compact, get statistics profile and
perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.
userAdmin This role allows the user to create and modify user accounts on
the database.
-
For example
db.createUser(
{
user: "sysAdmin',
pwd: "pass123",
roles:['readWrite',"dbAdmin"]
):
mongosh mongodb:t/127.0.0. X
test> db.createUser(
user: sysÅdmin",
pwd: "passl23"
roles: "readwrite", "dbAdmin"]
{ ok:
test>
TECHNICAL PUBLICATIONs- an
up-thrust for knowledge
Full Slack Web Dovelopment MONGO DB
3- 17
Syntax
db.dropUser(username)
For cxample
mongosh mongodb://127.0.0. X
test> db.dropUser("sysAdmin");
}
{ ok:
1
test>
Review Questions
Explain how to create users in MongoDB? Also enlist and explain various roles of the
USers.
2. How will you remove the user in MongoDB ? Explain.
For configuring the access control, the first step is to implement User Administrator
account.
can grant any privilege in the database and can create new ones.
In a MongoDB deployment, create the User Administrator as the first user.
But
not manage the database.
Syntax for creating the user administrator account is as follows -
use admin
b.createUser(
user:"<usemame>",
Pwd:"<password>"
Roles: ["userAdminAnyDatabase]})
For example
mongoshongod270D X
admin>
ongot mongolecede x X
TECNCAL PUBLCATIONS-an
up-thrust for knoatedge
MONGO DB
Full Stack Web Development 3-19
mongosh mongodb://<crede X X
mongosh mongedb://<crede
X
roles: ["readWriteAnyDatabase"
{
ok: 1}
admin>
Review Question
account in
1. Explain with suitable example how to create databaIse administrator
MongoDB ?
Review Question
1. Give various data npes used in MongoDB.
mongosh mongodb//127.0.0.
TECHNICAL PUBLICATIONs- an
up-thrust for knowedge
Full Stack Web Development 3- 21 MONGO DB
mystudents> db
mystudents
mystudents>
A mongosh mongodb://127.0.0.
Note that in above listing we can not see the mystudents database. This is because we have
not inserted any document into it. To get the name of the database in the listing by means of
show command, there should be some record present in the database.
(3) DropDatabase
is used to delete the database. For -
The dropDatabase() command example
mongosh mongodb/n27.0.0. X
mystudents> db.dropDatabase ()
{ ok:
, dropped: 'nystudents' }
nystudents>
TECHNICAL PUBLICATIONS
-
an up-thrust for knowledge
Full Stack Web Development 3-22 MONGO DB
Review Question
1. Write the MongoDB command to create and drop the database.
Syntax
db.createCollection(name,options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters such as size,
maximum number of documents and so on.
Following is a list of such options.
Field Type Description
capped Boolean Capped collection is a fixed size collection. It automatically
overwrites the oldest entries when it reaches to maximum size. If it
is set to true, enabled a capped collection. When you specify this
value as true, you need to specify the size parameter.
autolndexID Boolean This field is required to create index id automatically. Its default
value is false.
SIZe Number This value indicates the maximum size in bytes for a
clapped
collection.
Max Number Itspecifies the maximum number of documents allowed in capped
collection.
For example - Following command shows how to create collection in a database using
explicit command
mongosh mongodtin27.00.
nyStudents>
mongosh mongodb://127.0.0. %
+
3) Drop Collection
The drop collection command is actually used to remove the collection completely from
the database. The drop command removes a collection completely from database.
Syntax
db.collection name.drop)
For example
mongosh mongodb://127.0.0. X
myStudents> db.Student_details.drop();
true
myStudents>.
database
of the collection by using "show collections"
in the
We can verify the deletion
mongosh mongodb//127.0.0. x
mongosh mongodb:/27.D.0.
myStudents>
myStudents>
Emongosh mongodb//12700.X
"nane":"BB8",
"age":
"nane" "DDD",
"age":1
;
nyStudents> db.Student_details. insert (allStudents)
acknowledged tet :
insertedIds:
0bjctId("643e513d436497399ala2a67")
*0': 8d436497399ala2a68")
"1': 0bjectId("643e51
nyStudents>
To verify the existence of these documents in the collection you can use find command as
follows -
mongosh mongodb://127.0.0.
myStudents> db.Student_details.find()
ObjectId("643e4b63436497399ala2a66") name: 'AAA age: 22 },
,
{
-id: 0biectId("643e518d436497399ala2a67 "), name: '888 age: 29 }.
{-id: ObiectId("643e518d436497399ala2a68 "), name: 'DDD', age: }
{_id: 2i
myStudents>
6) Delete Documents
For deleting the document the remove command is used. This is the simplest command.
For example
can find out the documents
present in the collection using find() command
First of all we
mongodb:tn27.00.
mongosh
db.Student_details.find()
nyStudents>0bjectIJ("643eUb63436497399ala2a66"),
0bjectId("643e518d436u97399ala2a67" nàme: AAA', age: 22 }
name : 'BBB age: 20
id: ), }.
{ id:
nyStudents>
-
as follows
a record with name "DDD" we can issue the command
Now to delete
X
mongosh mongodb:N270.0.
db.Student_details.deleteOne({"name":"DDD"})::
yStudents> deletedCount: }
I acknowledged: tue,
yStudents>
mongosh mongodb:/27.0.0.
x
()
find
.
yStudents>
mangosh mongodo//12790
verifythatthe
Wecan verifyit using db.Student_details.find) command, we can
are deleted or not.
TECHNICAL PUBLICATIONSB- an
up-thrust for knowledge
Full Stack Web Development
3-27 MONGO DB
mongosh mongodb//127.0.0
myStudents> db.Student_details.Find)
myStudents>
8) Update Documents
For updating the document we have to provide some criteria based on which the
document
can be updated.
Syntax
db.collection name.update(oriteria,update data)
For example - Suppose the collection "Student details" contan following documents
mongosh mongodb:l/127.0.0.
.
And we want to change the name CCC" to "Www", then the command can be issued
as
mongosh mongodtb://27.0.0.
myStudents> db.Student_details. update({"nane*:"CCC*},sen"nane ")
DeprecationWarning: Collection. update() is deprecated. Use updateOne, updateany, or
bulkWrite.
acknowledged: true,
insertedId: nulL,
matçhedCount:
nodifiedCount
,
upsertedCount :
mongosh mongodb://127.0.0.
nongosh mongodb:NZT0.0. X
mongosth mongodbt127.00. X
myStudents> db.Student_details.find().sort({"age":-)
id: 0biectId("643e73b2436497399ala2a6c"), nane: 'DDD', age: 28 },
id: ObiectId("643e72de436497399ala2a69"), nane: 'AAA', age: 22 },
id: ObjectId("643e73b2436497399ala2a6b"),name: age: 21
id: ObjectId("643e73b2436497399ala2a6a"), name: 'BBB I
age: 29
nyStudents>
Review Question
1.. Explain with suitable examples, CRUD operations in MongoDB.
TECHNICAL PUBLICATIONS-
an up-thrust for
knowledge
Full Stack Web Development MONGO DB
3-29
client.connect()
then(()=>console.log("Connected to Database Successfully!!!"))
.catch(error=> console.log(Failed to Connect',error)
getData();
Output
to create a database.
a
we are using connect method by passing the above URL. Inside this function
5) Then
name "myStudents".
database object is created by a database
nccessary to install the mongodb
Note that before execution of the above code, it is
package using the following command at the current working directory.
Prompt:>npm install mongodb
Review Question
1. What are the steps to connect Node,js with MongoDB?
db(dbname, options) It creates a new DB instance sharing the current socket connections.
TECHNICAL PUBLICATIONS°-
an up-thrust forknowledge
Full Slack Web Development MONGO DB
3-31
Collections(options,callbacks) This method fetches all thecollections for current db.
dropCollection(name, options, callback) It drops the collection from the database, removing it
permanently.
listCollcctions( filter, options) This method is used to get the list of all the collection
information for the specified db.
Review Questions
1. Explan the MongoDBClient object and the methods associated with it.
2. Explain the db object and the methods associated with it.
Step 2 Open the command prompt go to the path of StudentDBDemo. And issue the
commands
D:\NodeJSExamples\StudentDBDemo>npm init
gets created.
And press enter key to accept the default values. By this package.json file
Step Then install the mongodb module using following command
3:
D:
NodeJSExamples\StudentDBDemo>npm install mongodb
getData();
Output
:
Program Explanation In above code,
1) First of all, we have to import the module 'mongodb' using require. Thus we are
creating MongoDB client.
2) Then specify the URL for MongoDB by means of hostname (localhost or 127.0.0.1)
and port number on which MongoDB is running (27017). This is a path at which we
are going to create a database.
3) Then we are using connect method by passing the above URL. Inside this function a
2) Insertion of document
Once the collection is created, we can insert some
document into it. Following 1s all
example code which shows how to insert one document into a collection named Student Into
const Mongo Client require(mongodb').MongoClient;
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
Full Stack Web Development MONGO DB
3-33
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
/ Connect to the database
const database = "studentsDB":
async function getData()
getData():
Output
:
Program explanation In above code,
1) First of all, we have to import the module 'mongodb' using require. Thus we are
creating MongoDB client.
2) Then specify the URL for MongoDB by means of hostname(localhost) and port
number on which MongoDB is running(27017). This is a path at which our database
exists.
a
3) Then we are using connect method by passing the above URL. Inside this function
database object is created by a database name "studentDB". Thus now we can access
to student DB
4) Then a JSON object is in the form (name:value}. We insert data in the collection in
the form of document. This document is created in the form of JSON. Hence the
mydata object is created with some values.
5) This mydata is inserted into the collection using insertOne method using following
code
dbo.collection("Student Info").insertOne(mydata)
can insert many documents in the collection.
In the same manner we
1:
dbo.collection(Student Info").insertMany(mydata):
console.log(Multiple documents Inserted!"):
getData(0:
Output
:
Program explanation In above code
We have created array of values in JSON object as Follows
yar mydata = 1
TECHNICAL PUBLCATIONSB
an up-thrust for knowledge
Fut Stack Web Development MONGO DB
3-35
Open MongoDB Compass. just connect with mongodb:/localhost:27017, select the
StudentDB database and then select Student Info collection. The following sereenshot
displays multiple documents inserted into it.
studentsDB.Student_Info 5
DCCUME
Field: vlun
5
Find Mo
S
ADD DATA C EXPORT COLLECT1ON I-5 of
„id: 0bjectId('G43d162b6265F487895e799*i
name "Anki ta"
city: "Pune"
)
1d: Object Id('6449dfd84be9f6c8e5eabsbe'
name: "BBB Multiple
c1ty: "Mumbai"
documents are
inserted in the
_id: 0bjectId(' 6449dfd84be9f6coeSeab6bf) database.
name: "CCC"
city: "Chennai"
_id: 0bjectId('6440dfd84be9f6cte5eab6ce')
name: "DDDn
city: "De Lhi
Display.js
const MongoClient = require(mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(rl):
I/Connect to the dabase
Const database= "studentsDB";
async function getData()
getData();
Output
TERMINAL
DEBUG CONSOLE
PROBLEMS OUTPUT
E:\NodeJSExamples\StudentDBDemo> display.js
node
PS
objectId("643fd162b6265f487395e709");
new
id:
name:Ankita
objectd("6440dfdg4begf6coe5eab6be),
new
id:
name: BBB
Mumbai'
city:
new objectId("6440dfdaabe9f6cee5eab6bf"),
id:
name: 'CCC,
city:Chennai"
new
id: objectd("6449dfd84begf6coe5eab6co")
name: DDD
city: Delhi'
city: Ahmedatbad
: In
Program explanation above code.
we
4) First of all. have to import the module 'mongodb' using we are
require. Thus
creating MongoDB client.
5) Then specify the URL for MongoDB by means port
of hostname(localhost) and
number on which MongoDB database
is running(27017). This
is a path at which our
exists.
TECHNICAL
PUBLICATIONS-
an up-thrust
for knowledge
Full Stack Web Development 3-37 MONGO DB
6) Then we are using connect method by passing the above URL. Inside this function a
database object is created by a database name "studentDB". Thus now we can access
to studentDB.
7) Then for reading the contents present in the documents of the collection we use the
find) method.
8) We use toArray method associated with the find) because it returns an array that
contains all documents returned by the cursor.
4) Update document
We can modify the document using updateOne method. Following code illustrates it -
Update.js
const MongoClient = require('mongodb).MongoClient;
const url="mongodb://127.0.0.1:27017";:
Const client new MongoClient(url);
/Connect to the dabase
const database = "studentsDB";
async function getData()
getData();
Output
PS
E:\NodeJSExamples\StudentDBDemo> node update.js
One Document Updated!!!
Filter Find
query: field: 'value' Reset
]
4
Type a
of 5
ADD DATA
C EXPORT COLLECTION 1-5
city: "Chennai"
:
Program explanation In above code,
We are updating one document using updateOne method. This method require two
parameter first one is the existing data and second one is the new data which you want to put
in place of the existing one. This can be done with the help of following lines of code
var mydata = {name: "DDD}; Jlezisting record with name "DDD"
var newdate = {Sset: {namne:1T city:"Jaypur} //replace it by a new data
Then updateOne method is called by passing these two parameters.
5) Delete document
This is the operation in which we are simply deleting the desired document. Here to delete
a single record we have used deleteOne method. The
code is as follows -
deleteDne.js
const MongoClient require(mongodb'), MongoClient;
const urd ="mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
11Connect to the dabase
const database = "studentsDB;
async function getData(0
TECHNICAL PUBLICATIONSan
up-thrust tor knowiedge
Full Stack Web Development 3-39 MONGO DB
dbo.collection("Student Info").deleteOne(mydata):
console.log('One Document Deleted!!"):
getData():
Output
We can verify it using MongoDB Compass. Note that the name TTT is missing.
id: 0bjectId('6440dfd84be9f6c@eseab6be')
name: "BB8"
city: "Humbai"
0bjectId('644@dfds4be9r6cêe5eabác1)
id:
name: "EEE
city: "Ahnedabad"
The above deletion operation can be veritied by displaying the contents of the collection
new ObjectId
id: 643fd62b6265F487895e709")»
name:Ankita
city:Pune'
new
id:
name: BBB
objectd("6440dfds4begf6coe5eab6be") Note that the
document
city: Mumibai
containing the
name field
new objectId("6440dfd8abe9f6cbeSeab6bf"), with value
id: "TTT" is not
name:COC
city: Chennai present.
new objectid("6A40dfd84be9f6coeSeab5c1"),
id:
name: EEE,
city: 'Ahmedabad'
6) Sorting documents
Data can be arranged in sorted order in the collection. For displaying the sorted ordered
data we use the method sort. Following code illustrates how to display the data in ascending
order of the filed named city.
Sort.js
const MongoClient = require('mongodb).MongoClient;
const url="mongodb://127.0.0.1:27017";
const client = new MongoCient(url);
// Connect to the dabase
const database = "studentsDB";
async function getData()
{
getData();
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development
3- 41 MONGO DB
Output
new Objectd("6440dfd8Abegf6cleseab6bf"),
id:
name: 'CCC
city: 'chennai
new
id: objectd("643fd162b6265f487395e709"),
name: Ankita",
city: Pune
Program explanation : Inabove code to sort in ascending order we use sort. The key field
based on which the document is to be sorted is city. We have passed 1 along with it for
displaying the city names in ascending order. If we pass -I then the cities are displayed in
descending order. Simply change the above code as
var mydata = { city: -1};
Review Questions
1. Explain insertion and deletion database operation using NodeJs.
2. Write aprogram to display the sorted data in the database using NodeJs.
3. What is CRD ? Eyplain the CRUD operations in node,js.
3.11 Advanced MongoDB
Following are the features of advanced MongoDB.
3.11.1 Indexing
For efficient execution of queries the indexing is used. If' we use the query without indexes
then the execution of that query will be very slow.
Definition of indexIndex is a special data structure that store small part
:
of collection's
data in such a way that we can use it in queryng.
1) Index creation
Syntax for creating index is
db.<collection>.createlndex({KEY:1})
The key determines the field on the basis of which the index is created. After the colon the
direction of the key( 1l or -1) is used to indicate ascending or descending order.
The MongoDB will generate index names by concatenating the indexed keys with the
direction of each key with underscore as separator. For example if the index is on the field
name and the order as 1 then the index will be created as name 1.
We can also use name option to defne custom index name while creating the index.
-
For example
> db.Student details.createlndex({nane:1}, {name:'Student's Names"} )
-
The result will be as follows
"reatedlollectionAutonatically" false,
"numIndexesbefore"
:
2,
"re IndexesAfter"
:
3.
1
"ok;
TECHNICAL PUBLICATIONSan
up-thrust for knowiedge
Full Stack Web Development MONGO DB
3- 43
2) Find index
We can find all the available indexes in the MongoDB by using getindexes method.
Syntax
db.<collection>.getIndexes()
-
For example
>db.Student_details.getindexes()
The result will be
GComnmand Prompt- mongo
db.Student_details.getIndexes()
"v": 2,
:
"key" :
" id" 1
:
"name" "id_"
"v": 2,
"key" : {
"name" : 1
:
"name" "Student's Names"
Note that the output contains the defaultid index and user created index.
3) Drop index
To delete an index we use droplndex method.
Syntax
db.<colection>.droplndex(Index Name)
For examnple
db.Student details.droplndex("Student'sNames")
4) Compound index
We can create index on multiple fields in MongoDB document. For
example
It will sort by name in ascending order and age in descending order. If the names are same
then the descending order of age can be noticed.
3.11.2 Aggregation
Aggregation is an operation used to process the data that results the computed results. The
aggregation groups the data from multiple documents and operate on grouped data to gct the
combined result. The MongoDB aggregation is cquivalent to count(*) and with group by in
sql. MongoDB supports the concept of aggregation framework. The typical pipcline of
-
aggregation framework is as follows
Input Output
Smatch Sgroup $sort
1) Smatch) stage - Filters those documents we need to work with, those that fit our
needs.
2) Sgroup) stage - Does the aggregation job.
3) Ssort() stage - Sorts the resulting documents the way we require (ascending or
descending).
The input of the pipeline can be one or several collections. The pipeline then performs
successive transformations on the data and the result is obtained.
Syntax for aggregate operation
db.colection name.aggregate(aggregate operation)
Demo example
For demonstration purpose, I have created a database named CustomerDB inside which
there is a collection document named customers. Some data is already inserted into it. The
contents of customers document are as shown below -
-
Command Prompt mongo X
> use CustonerDB
Sitched to db CustomerDB
db.customers.find()
i. CbiectId("610e57c112Be95223b716fcf"), "name": "AAA", "type":"Develoner" )
: objectId("610e57ff128e95223b716fde" ), "name" : "BBg".
id
"type" : "Tester" }
id" : objectd("610e5834128e95223b716fd1"), ,
"name"
ObjectId("610e585c128Be95223b716fd2") "nane"
"CCC", "type" : "Tester" }
k"id": : ObiectId("610e587d128e95223b71ófd3"), "DDD", "type": "Developer"
}
I34 "name" :"EEE", "type" : "Developer )
TECHNICAL PUBLICATIONS-an
up-thrust for knowledge
Full Stack Web Development
3- 45 MONGO DB
-
The above command willdisplay total categories of the customers In our database there
are two types of customers -"Developer" and Tester". There are 3 developers and 2 testers in
the collection document. The aggregate function is applied on the Sgroup.
Similarly if we want to find only Developers from the collection document customers then
we use Smatch for aggregate function. The demonstration is as follows -
- mongo
Ci Command Prompt
db.customers. aggregate([{Smatch : (type:"Developer"}}1)
: :
"_id" ObjectId("610e57c1128e95223b716fcf"), "name "AAA"
","type "Deve loper" }
"_id" : 0bjectId("610e585c128e95223b716fd2"), *name" "DDD", "type" "Developer" }
:
"_id" ObjectId ("610e587d128e95223b716fd3"), "name" "EEE", "type "Developer" }
Savg Calculates the average values from all the documents in a collection
Where
1) map Function : It uses emit() function in which it takes two parameters key and value
key. Here the key is on which we make groups(such as group by name, or age) and the
second parameter is on which aggregation is performed like avg0, sum) is.calculated
on.
2) reduce Function: This is a function in which we perform aggregate functions like
avg), sum)
3) out : It will specify the collection name where the result will be stored.
4) query We will pass the query to filter the resultset.
:
Demo Example :
Step 1 : Create a collection inside the database mystudents. The collection is created using
name Student info.
|>use mystudents
switched to db mystudents
db.createCollection("Student_info")
i : 1 }
"ok"
Step 2 : Now we will insert documents inside the collection Student info using following
command
db.Student info.insertMany( [
{name:"Ankita", marks:96}.
{name:'Ankita", marks:86).,
{name:"Ankita", marks:92},
{name:"Kavita", marks:87).
{name:"'Kavita", marks:74},
{name:"Kavita", marks:86 }
1)
Now in order to display the contents of the collection we issue the find) command.
Command Prompt - mongo X
db.Student_info.find() .pretty() 4 -Issue this command to display the documents in the collection
"_id" : ObjectId("6110ce2 a85089e2d2c7fac22"),
"name": "Ankita",
"marks": 96
"name": "Ankita",
"marks" . 92
" id" : objectId ("6110ce2a85es9e242c7fac25"),
"name :
"Kavita",
: 87
"marks"
"_id"
:
ObjectId("611ece2a85089e2d2 c7fac27"),
:
"name" "Kavita",
"marks" : 86
EC Command Prompt
- mongo Create a 'map' function
which stored name and
>
var map = function() { emit(this.name, this.marks);};: D
marks fields
> var reduce = function (name, marks) {return Array.sum(marks);}:.
>
db.Student_info.mapReduce( Create a 'reduce'
map, -Pass both the 'map' function that
reduce,
(out:"Result"}
and 'reduce' finds the sum of
.. ): functions to
mapReduce and
allthe marks of
: 1 } each student
{"result" "Result", "ok"
:
create a collection
named "Result".
Advantages of mapReduce
1) MapReduce allows the developer to store complex result in separate collection.
2) MapReduce provides the tools to create incremental aggregation over large collections.
3) It is flexible.
Review Questions
1. List and explain thefeatures of advanced MongoDB.
2. What is the purpose of mapReduce. Explain it with suitable example.
Ans. :
1) It is a
schema-less, document based database system.
2) It provides high performance data persistence.
3) It supports multiple storage engines.
4) It has a rich query language support.
5) MongoDB provides high availability and redundancy with the help of replication.
That means it creates multiple copies of the data and sends these copies to a different server
-sothat if one server fails, then the data is retrieved from another server.
Q.4 How the terms in MongoDB are different from SQL ?
Ans. The terms in SQL are treated differently in MongoDB. In MongoDB the data is not
:
stored in tables, instead of that, the there is a concept called collection which is analogous to the
tables. In the same manner the rows in RDBMS are called documents in MongoDB, likewise
the columns of the record in RDBMS are called fields.
Q.5 Explain the createUser command in MongoDB.
Ans. :
The user accounts are created using the createUser) method.
Stax
db.createUser(user, wIiteConcerm)
Parameters
user: Is a document with authentication and access information about the user to create.
writeConcern: This document represents the level ofwrite concern for creation operation.
Q.6 How remove users from MongoDB ?
For removing the user, the db.dropUser( is used.
:
Ans.
Syntax
db.dropUser(usernsme)
Q.7 Enlist any four data types in MongoDB.
Ans. Following are various types of data types supported by MongoDB.
:
numerical value.
1) Integer: This data type is used for storing the
i.e. true or false.
2) Boolean: This data type is used for implementing the Boolean values
3) Double Double is used for storing floating point data.
:
4) String: This is the most commonly used data type used for storing the
string values.
BSON element.
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
Full Stack Web Development 3-50 MONGO DB
For storing an array or list of multiple values in one key, this data type is usecd.
:
6) Arrays
Syntax
db.createCollection(name,options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters such as size,
maximum number of documents and so on.
Q.9 How to insert multiple documents in a MongoDB database ?
Ans. :
It is possible to insert multiple documents at a time using a single command. Following
"name": AAA,
"age": 20
}.
{
"name: BBB,
"age": 21
"name": CCC,
"age": 22
1:
>db.Student details.insert(allStudents):
Q.10 Explain the MongoDBClient in detail.
Ans. : The MongoDBClient object provides interactions to connect to the
database. Following
are some commonly used method of MongoDBClient object.
Method Purpose
connect(url,options) This method is used to connect to the MongoDB
using the specified url.
close(force, callback) This method closes the db and underlying
connections.
TECHNICAL PUBLICATIONS-
an up-thrust for knowedge
Full Stack Web Development MONGO DB
3-51
db(dbname, options) It creates a new DB instance sharing the current socket connections.
Map reduce is used for large volume of data. The syntax for map reduce is
>db.collection.mapReduce(
function(0 {emit(key,value):}, <-map function
|function(key,values) {return reduceFunction}, { <-reduce function
Out: collection, <-the collection is created in which the result of mapReduce can be stored
query: document,
sort: document,
limit: number
Where
1) map function : It uses emit) function in which it takes two parameters key and value key.
Here the key is on which we make groups(such as group by name, or age) and the second
parameter is on which aggregation is performed like avg), sum) is calculated on.
2) reduce function :
This is a function in which we perform aggregate functions like avg0,
sum()
3) out : It will specify the collection name where the result will be stored.
Notes
TECHNICAL PUBLICATIONS-
an up-thrust for
knowledge
UNIT IV
4
Syllabus
Express and Angular
Implementing Express in Node.js - Configuring routes - Using Request and Response objects
Angular - Typescript - Angular Components - Expressions - Duta binding Built-in directives.
-
Contents
4.1 Implementing Express in Node,js
4.2 Configuring Routes
4.3 Using Request and Response Objects
4.4 Introduction to TypeScript
4.5 Type Annotations
(4- 1)
Full Stack Web Development Express and Angular
4-2
Part I: Express
app.getT, function(regres){
Greate a Ioute. This is a
res,sendCWelcome Userl!); default route
Output
On the terminal window or on command prompt window issue the command
> node appjs
Open some web browser and issue the URL "localhost: 8082"
(x
localhost8082
O localhost:8082
Welcome User!!
:
Program example In above code,
I) We have imported express.js module using require function. The express module
returns a function and this function returns an object. This object can be used to
configure the Express application. In above code, it is the app object.
-
2) The app is an instance of express module. To the method of this instance The
can be passed. The general
HTTP request, response objects and a callback function
syntax is
app.method(path, handler)
here,
is an HTTP GET, PUT, POST
or DELETE
method
handler is the function executed when the route is matched.
3) Then using the app.listen to function to make our server application listen to client
requests on port number 808.2. We can specify any desired port number.
json spaces It specifies the number of spaces to use when creating the JSON response. The
default value in development is 2 and 0 in production.
json replacer It defines the JSON replacer callback function. Default value is NULL.
view engine It specifies the default template engine extension while displaying the web page.
views For specifying the path for template engine it is used. Template engine is a package
that renders the data or values in HTML pages.
app.get(, function(req,res) {
res.send("Welcome User!!"):
}:
I/routing to 'about us' page
app.get(/about', function(reg.res) {
res.send("This is about us page"):
}):
I/routing to 'contact' page
app.get(/contact', function(reg,res) {
res.send("This is displays contact information");
}):
X
S localhost:8032/about X +
localhost:8082/about
S localhost:8082/contact X +
O localhost:8082/contact
Request object
The properties and methods of request object are as follows -
Properties /Methods Deseription
req.app This property is used to hold a reference to the instance of the express
application.
req.accepts(types) It is used to check content types are acceptable, based on the request's
Accept HTTP header field. For example
req.accepis("html');
req.get(field) This method returns the specified HTTP request header field.
Output
Program explanation In above program, we have called various methods of Request object
:
Response object
response object.
• Following are some properties and methods of
Properties / Methods Description
It holds a reference to the instance of the express application that
res.app is using the middleware.
TECHNICAL PUBLICATIONS- an
up-thrust for knowtedge
Full Stack Web Development 4-9 Express and Angular
Output
Response Demo +
O localhost:8082
Program explanation :
In above program,
We have created an HTML document in a variable new response. This document is sent
to browser using res.send method. Before sending this document to the browser we have set
the status code as 200 (i.e. OK) and the content-type and content length. The status of headers
sent is also displayed on the console window. For performing all these tasks, the
corresponding methods of Response object are used.
Part Il : TypeScript
The Type system increases the quality of code and readability. It makes the maintenance
of the code easier.
Using TypeScript the developer can catch the erors regarding type-system at the
compile time instead of run time. So that it can be fixcd casily before it gets conplex.
• Another important aspect of using TypeScript is its support for the use of object
oriented features in the scripting language.
Features of TypeScript
1. Portability : TypeScript is a portable because it can be executed on any browser or
operating system. It can run on any environment where JavaScript runs.
2. JavaScript : The code written in JavaScript with valid js extension can be converted
to TypeScript by simply changing the extension from js to .ts.
3. Static Type checking : This feature allows type checking at compile.
4. Support for Library : For developing the TypeScript coding we can se all JavaScript
frameworks, tools and libraries easily.
5. Support for OOP: The TypeScript can make use of various features of
object-oriented programming languages such as classes, interfaces, inheritance and
SO on.
6. Client and Server side Development : TypeScript allows the development of both
server-side and client-side programming.
Advantages
1. It is an open source language with continuous development.
2. It runs on any web browser.
3. The TypeScript code can be called from existing JavaScript code. It can also work
with JavaScript frameworks and libraries without any issue.
4. TypeScript has a support for the latest JavaScript feature from ECMAScript2015.
The ECMAScript specification is a standardized specification of a scripting
language. This standard is meant to ensure the interoperability of web pages across
different web browsers. The 6th edition, ECMAScript 6 (ES6) and later renamed to
ECMAScript 2015. Some of major enhancements of this standard include modules,
class declarations and so on.
Disadvantages
1
Weh browsers do not understand the TypeScript code. we want to run
If TypeScript
code in the web browser then we need to compile it. This compilation process
converts it to JavaScript and then we can see the TypeScript
code running in the web
browser.
TECHNICAL PUBLICATIONS -an
up-thrust for knowedge
Full Stack Web Development 4- 11 Express and Angular
C nodejs.org/en/
aede e
HOME ABOUT DOWNLOADS DOCS GET INVOLVED CERTIFICATION NEWS
SECURITY
#BlackLives Matter
Newsecurity releases now available for 15.x, 14.x, 12.x and 10.x
release lines
Download
Download node MSI for windows by clicking on 14. 16.0 LTS or 15.11.0 Current
button.
. Ater you download the MSI, double-click on it to start the installation as shown below.
Nodejs Setup
Click Next button to read and accept the License Agreement and then click Install. It
will install Node.js quickly on your computer. Finally, click finish to complete the
installation.
Verify Installation
• In order to verify the installation we have to open a
command prompt and type the
-
following command
Command Prompt
D:\>node -v
v14.15.4
D:\>
TECHNICAL PUBLICATIONS-
an up-thrust for knowlodge
Full Stack Web Development 4- 13 Expres and Angular
-
The screenshot is as follows
GN nprm X
Microsoft Windows [Version 10.0.19843.1415]
l(c) Microsoft Corporation. Al1 rights reserved.
C:\Users\DELL>npm install -g typescript
nt
..]/ extract:typescript: lock using C:\Users\DELL\AppDat
any project.
Thabove command will install TypeScript globally so that we can use :
it in
Now check the installed version of TypeScript using the following command
tsc -v
G CAWindows\system32\cmd.exe X
C:\Users\DELL>tsc -V
Version 4.5.4
C:\Users\DELL>
That's it!. We can now vrite and execute our TypeScript programs.
myfirstprog.ts
console.log("Welcome to my First TypeScript Programll!"):
T5 myfirstprog.ts Xx
EXPLORER
IypeScript A
O0AO
Ln 1 Col 59 Tab Sze 4 UTF8 CRLF
0
tsc myfirstprog.ts
-
Following screenshot illustrates it
X
CAWindowsisystem32\cmdexe
E:1TypeScript_Code>tsc myfirstprog.ts
E:1TypeScript_Code>
By this step your typescript code is converted to plain javascript code. That means ou
compiling the myfirstprog.ts the myfirstprogjs file gets generated.
TECHNICAL PUBLICATIONS
'- an up-thrust for knowlodge
Full Stack Web Development Express and Angular
4-15
CAWindows\system32\cmd exe
Directory of E:\TypeScript_Code
|27-12-2021 15:23 <DIR>
27-12- 2021 15:23 <DIR>
27-12-2021 15:23 60 myfirstprog.js
27-12-2021 15:19 58 myfirstprog.ts
2 File(s) 118 bytes
Dir(s) 303,098,732,544 bytes free
E:1Typescript_Code>
Step 4 :
Now we can get the-output of the above program on the web browser. For that
purpose we have create an index.html file by adding new file under typescript-code
folder and call the myfirstprog.js file in it. The code is as follows
index.html
<html>
<body>
<script src ="myfirstprogjs"> </script>
</body>
</html>
Just refer following screenshot
View indexhtm! -TypeScript_Code-Visual
* File Edit Selection Go Run
EXPLORER
<>
index.html
>
index.html
<
V TYPESCRIPT CODE
Ln 6. Col Spaces 4
UTF-8 CRLF HTML O
on browser
Step 5 :
Open some web browser and enter the path of the file as URL, right click
window. Select Inspect-> Console. The output can be viewed on Console window.
-
It is as follows
index.html
Reading list
Apps
Sources
B1 X
Elements Console
Default levels
top Filter
1
Issue: F1
my
Welcome to First TypeScript Program! !!!
Review Questions
1. What is TypeScript ? Give the advantages and isadvantages of using it.
2. List and explain the features of TypeScript.
3. Write a TypeScript to display a welcome message.
TECHNICAL
PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development Express and Angular
4- 17
Variables can be declared using var and let. The contestant can be declared using const.
var
Thevariable can be declared using the keyword var same as JavaScript. To assign a value
to the variable, use the equal sign.
var studName = "Parth":
let
The let declaration follows the same syntax as var declaration. For example -
let empName = "Archana"
The var declaration has some problems in solving programs, so ES6 introduced let
keyword to declare a variable in TypeScript and JavaScript. The let keyword has some
restriction in scoping in comparison of the var keyword.
Difference between var and let
Var declarations are globally scoped or function /locally scoped. The scope is global when
a var variable is declared outside a function. This means that any variable that is declared with
var outside a function block is available for use in the whole window. For example
for (vari=0;i<5; i++) {
console.log("i=", i);
i= 4
Outside the loop: i = 5
The let keyword is block scoped. The block is defined within
{ . It means that the
variableionly exists and can be accessible inside the for loop block.
For example -
for (let i= 0;i< 5; i++)
console.log("i=", i);
The above code gives the error as, we have used console.log statement displaying the value
of ioutside the block.
const
.
Variables declared with the const maintain constant values. Like let declarations, const
declarations can only be accessed within the block they were declared. The const cannot be
updated or re-declared.
This means that the value of a variable declared with const remains the same within its
Scope. It cannot be updated or re-declared. So if we declare a variable with const, we can
:
neither do this
Const name ="Ankita":
greeting = "Prajkta;
4) While creating the object for the interface function, it should refer to the
implemented function.
5) While defining the function inside the interface variable type and function return type
should be mentioned properly.
6) While implementing the function which is defined in the interface, the method
signature must be matched properly.
name:string,
rollno:number
var students:studentType = {
name:Parth!.
rollno:101
console.warn(students);
Step 2:Now open the command prompt window and issue the command tsc app.ts. This will
created app.js file internally. Execute this .js file as well. Following screenshot illustrates it -
E:\TypescriptExamples>tsc app.ts
E:\TypescriptExamples>node app.js
f name: Parth', rollno: 101 }
E:\TypescriptExamples>|
var students:studentType ={
name:Parth,
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
Full Stack Web Development 4-20 Express and Angular
rollno:101,
display_message(){return "Hello "+students.name:).
console.wam(students.display message());:
Output
E:\TypescriptExamples>tsc app.ts
E:\TypesriptExamples>node app.js
Hello Parth
E:\TypescriptExamples
Example 4.7.1 Write acode in TypeScript 1o implement the simple arithmetic calculator
application. Make use of interface.
Solution:
app.ts
interface mycalculator {
(anumber,b:number):Number:
function addition(a:numbe,bnumber):number{
console.log('a ="+a);
console.log("b ="+b):
return a+b;
}
function subtraction(anumber,b:number)number{
console.log('a = +a);
console.log("b = +b);
returm a-b;
}
function multiplication(a:number,b:number):number{
console.log('a = +a);
console.log("b = "+b);
return a*b;
function division(a:number,b:number):number{
console.log('a = "+a);
console.log("b ="+b);
return a/b;
E:\TypescriptExamples\Calci>tsc app.ts
E:\TypescriptExamples\calcinode app.js
*****k* DEMO OF CAL CUIATOR ******
a = 10
b = 20
= 30
Result of addition
a = 20
b= 10
= 10
Result of subtraction
a = 10
b= 20
=
Result of multiplication 206
a = 20
b= 10
= 2
Result of division
E:\TypescriptExamples\calci>l
Review Questions
1. What is interface ? Explain the use of interfaces in TypeScript with suitable example.
2. What are the rules for using interfaces.
Example
class Person {
person id: number;
Properties
person name: string;
gétName:string {
Method
retum "Parth":
}
Jsing constructor
The constructor is a special type of method which is called when creating an object. In
IypeScript, the constructor method is always defined with the name "constructor".
• Example
class Person {
getName:string { Method
return "Parth":
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
FullStack Web Development 4- 23 Express and Angular
Creating an object
Anobject is an instance of a class. The object is created using keyword new.
For example -
app.ts
class Person (
person id: number;
person name: string:
constructor(id: number, name: string) {
this.person id = id;
this.person name = name;
E:\TypescriptExamples\ClassDemo>tsc app.ts
E:\TypescriptExamples\ClassDemo>node app.js
Person person id: 101, person name: "Parth
{ }
E:\TypescriptExamples\ClassDemo>
Inheritance
Inheritance. is a important feature of object oriented programnming in which the child
classes are created by inheriting some of the properties of parent class. The keyword
extends is used to inherit the child class from parent class.
Example
class Person {
pname:string: Parent Class
constructor(name: string) {
this.pname = name;
constructor(name:string,rol:number){
super(name);
this.rollno = roll;
}
display():void {
console.log("Roll Number: ", this.rollno);
console.log("Name: ",this.pname);
}
var stud = new Student("Parth 101);
console.warm(stud);
Output
CAWINDOWS\system32\cmd.
E:\TypeScriptExamples\InheritanceDemo>tsc app.ts
E:\TypeScriptExamples\InheritanceDemo>node app.js
Student { pname: 'Parth', rollno: 101
}
E:\TypeScriptExamples\ InheritanceDemo>
Review Questions
1. What is class ? How to use class in TypeScript ? Explain it
with suitable example.
2. Explain the use of inheritance in TypeScript with suitable example.
TECHNICAL PUBLICATIONSD
an up-thrust for
knowledge
Full Stack Web Development 4- 25 Express and Angular
Weusethe prefix export with all the definitions which we want to include in a imodule and
want to access from other modules.
Demo example
Step 1 : We will create calculator.js is a module which contains a
class named Addition.
This class is prefixed with keyword export.
calculator.js
export class Addition {
a: number;
b: number;
b: number) {
constructor(a: number,
this.a = a;
this.b = b;
display(){
console.log ("Addition:" +
(this.a + this.b) );
The above class contains two variables a and b. It also contains one function display).
Step 2: Now we willcreate one JavaScript file for importing the class created in above step.
Definition import : A module can be used in another module using an import statement.
:
Syntax
import { export name } from "file path without extension"
Following file is used for import file.
app.ts
import {Addition) from /calculator;
C Command Prompt
E:\TypeScript_Code\ModuleDemo>node ./app-js
Addition: 309
E:\TypeScript_Code\ModuleDemo>
1. None
2. CommonJS
3. AMD
4. UMD
5. System
6. ES6. ES2015 or ESNext
We have used CommonJS option for execution of JavaScript applications.
Following example illustrates how to import multiple classes in a single JavaScript file.
Step 1 :
Create a TypeScript program and define two classes namely Addition and
Multiplication
calculator.js
export class Addition {
a: number;
b: nunber;
constructor(a: number, b; number) {
this,a a
this.b = b;
display) {
console, log(Addition:"+ (this, a + this.b) );
this.a = a:
this.b b;
show()) {
console. log ("Multiplication:" + (this.a this.b) ):
CI Command Prompt X
E:\TypeScript_Code \ModuleDemo>
Review Question
1. Write a sample application in TypeScript to demonstrate the use of
moules.
Syntax
-
The function can be defined as follows
function function name([arg1, arg2,
.., argN) {
Ibody of function
num1+num2:
var result =
console.log(result):
addition(10,20);
Output
E:\TypeScriptExamples\FunctionDemo>tsc app.ts
E:\TypescriptExamples\FunctionDemo>node
app.js
30
E:\TypeScriptExamples\FunctionDemo
For example -
anonymous function
let display = function() //This is
console.log("Welcome");
return a+b;
console.logladdtion(10,20);
lamnbda
Arrow function calledas
also
The fat arrowfunction => is used for anonymous function. They are
functions.
Syntax
....
((arg1,arg2, argN|) => expression { I/function body}
By the use of => arrow we need not have to use the keyword function
For example -
let addtion = (a:number, b:number):number =>
return a+b:
console.log(addtion(10,20);
Review Question
1. Explain the arrow function in TypeScript with suitable example.
Part Il : Angular
5. Dynamic development : Angular team releases two versions in a year. This helps
the developer to have handy and updated functionalities cach time along with cach
new release.
6. Full stack development : The full stack development is a buzzword that start-up
companies use in this modern of software development. Angular is a complete
framework of JavaScript. It provides testing, animations and accessibility.
Review Question
1. What is angular ? List and explain its features.
While installing the node.js, the npm(node package manager) gets installed. Angular
requires NPM V6.11l or later. Hence we have to check the version of npmn by issuing following
command on the command prompt window.
S Command Prompt X
Microsoft Windows [Version 10.0.19043. 1415]
I(c) Microsoft Corporation. All rights reserved.
C:\Users\DELL>npm -v
6.14.10
C:\Users\DELL>
If you don't have the latest version of NPM, then update it using the following command on
Windows.
npm install -g npm
Step 3: Now install the Angular CLI. For that purpose create a folder in which we want to
install the Angular. Ihave created a folder named AngularDemo in E: drive.
npm
C:\Users\DELL>e:
E:1>mkdir AngularDemo
E:\>cd AngularDemo
E:\AngularDemo>npm instal1 -g @angular/cli
..] | loadDep:ssri: sill resolvewithNewModule balanced-ma
Step 4: We have to check version of installed Angular CLI by issuing the command
ng -
-version
os Command Prompt
how to change this setting, see https://angular. io/analytics. No
+ @angular/[email protected]
ladded 183 packages from 134 contributors in 290.655s
E:\AngularDemo>ng --version
to the first-app folder and issue the following command at the command prompt window
ng serve -o
TECHNICAL PUBLICATIONS an up-thrust for knowledge
Full Stack Web Development Express and Angular
4-32
-
Following screenshot illustrates it as
G Windows Powershel
E:\AngularDemo> cd first-app
E:\AngularDemo\first-app>ng serve -o
N Browser application bundle generation complete.
| Initial Total |
2.68 MB
Build at: -
Hash: Time: ms
Compiled successfully.
A FirstApp
0 localhost4200
O
A Welcome
A
+
Resources
Hee are some links to help you get started
Next Steps
What do you want to do next with your app?
Note that this is a default page. This script is present in the src folder in the
.
app.component. html file. This is a view file. We normally edit this file and the html script as
per our requirements.
Step 2 :
The <app-root> is defined as selector. In src->app folder. Just open the
app.component.ts. This file contains the selector as follows
@Component({
selector: 'app-root!,
templateUrl: '/app.component.html,
styleUrls: [./app.component.css]
)
Step 3: Inside the app.module.ts file the specification for AppComponent is mentione.
@NgModule({
declarations: [
AppComponent,
WelcomeComponent
1,
Step 4: This is the flow of execution Angular app. This app can be displayed in the browser
window when we issue the command ng serve -0 on command prompt or terminal
window.
TS app.module.ts X
16 AppComponent,
11 WelcomeComponent
12
13 inports: [
14 Browserodule,
15 AppRoutingodule
16
17 providers: [),
18 bootstrap: [Appomponent]
19
20 export class Appodule {}
21
exports : of declarations that should be visible and usable in the component templates of other
NgModules.
bootstrap : This is main application view called root component which hosts all other apps
views only. Only the root NgModule should set the bootstrap property.
3. Components
4. Data Binding
5. Directives
6. Metadata
7. Injections and Services.
Directives metadata
Modules
Module Module Template
Components Services
Property Event
Binding
metadata Binding
Module Module
Values Functions
Components
Injections
Services
2. Template
witlh Angular Markup and modiv
Template is basically used to combine HTML
HTML element before displaying them.
directives provide program logic and binding markup which connccts
Template
application data and DOM.
-
this
Typically in out Angular App the template looks like
<div style=text-align:center">
<h1>
//code for data binding
</h1>
</div>
3. Components
a class which basically contains the
The component in the application defines
application logic and data.
page is in
The application logic is normally written in TypeScript format and view of the
HTML template.
• A component controls a display of screen called a view.
Every Angular app has at least one component which is known as root component
which connects the component hierarchy with the page Document Object Model(DOM).
4. Data Binding
There are two types of data bindings -
1. Property Binding : This type of binding allows to pass the interpolated values from
application data to HTML. The interpolated values are specified in {{ and }}. bracket
pair. For instance - the student.name is interpolating value.
<p>Name: {{ student.name }}</p>
2. Event Binding: Event binding is used to capture events on the user's end on the apP
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development Express and Angular:
4- 37
ng-bind : This directive replaces the HTML control value with a specified AngularJS
expression value.
6. Metadata
Metadata means data about data.
Metadata tells Angular how to process a class. It is used todecorate the class so that it
can configure the expected behavior of a class.
The metadata for a component class has a template that defines a view.
The metadata for a service class consists of information Angular needs to make it
available to components through Dependency Injection (D).
7. Injections and Services
• In Angular,
itis a practice for data or logjc that it should not be associated with a
specific view. It is created as a service class. Due to this, the data or logic is shared
across Components.
By dependency injection, we mean to allow access to the service by subscribing it. It
acts as a delegate to the service.
• The @Injectable decorator immediately precedes the service class definition. The
decorator provides the metadata that allows our service to be injected into client
components as a dependency.
Review Question
1. Explain the angular architecture with suitable block diagram.
.
TECHNICAL PUBLICATIONS an up-thrust for knowedge
Full Stack Web Development 4-38 Express and Angular
can be viewed as
Typical organized page in Angular App contains multiple components. It
follows -
Footer component
We willcreate a component in a first-app application. Not its time to create a simple app.
There are two ways to create components - the component can be created manually or it
can be created using Angular CLI command. Let us now create a simple component using
Angular CLI method.
Demo Example
Step 1: Go to the first-app folder and issue the following command at the command line. Note
that the name of my component is welcome. You can give any name to the
component.
ng generate component welcome
PROBLENS OUTPUT DEBUG CONSOLE TERMINAL
EXPLORER
FIRST-APP
>angular
>VSCode
>node_modules
V src
app
welcome
# welcome.component.css
( welcome.component.html
TS welcome.component.spec.ts
TS welcome.component.ts
TS app-routing.module.ts
# app.component.css
app.component.html
TS app.component.spec.ts
TS app.component.ts
TS app.module.ts
Step We will keep our app.component.html file very simple. Delete everything from it
2: following code
which comes by default from the Angular framework and simply add
to it.
app.component.html
<h1>Hello </h1>
it as follows. The bold-faced code
Step 3 :
Now open welcome.component.ts file and edit
component.
shows the modification in the default .ts file of
constructor() {}
ngOninit(): void {
welcome.component.html
<p>welcome {{currentUser}}<p>
Step 5 :
Now open app.component.html file and edit it with the selector name of the
component.
app.component.html
<h1>Hello</h1>
Kapp-welcome><Japp-welcome>
Step 6 : Now open the command prompt and issue the command
ng serve-o
The application will get compiled and the browser window will get opened. up. The
welcome component will be added to it.
A FirstApp X
) localhost 4200
A
Hello
welcome Anuradha
+
If you want to add multiple time the same component, then simply edit your
app.component.html file as
app.component.html
<h1>Hello </h1>
<app-welcome> </app-welcome>
<app-welcome></app-welcome>
<app-welcome></app-welcome>
-
The output will be
A FirstApp X
O localhost:4200
A
Hello
welcome Anuradha
+
welcome Anuradha
welcome Anuradha
Review Question
1. Give the sample layout of the Angular application with multiple components.
Explain how to create and use thecomponets in Angular:.
4.16 Expressions
Angular evaluates expressions and then can dynamically add the results to
a web page.
as -
Expressions are encapsulated blocks of code inside brackets follows
{{ expression }}
For example
{{2+3 }} //output: 5
{{Java' + 'Program' }} /loutput: JavaProgram
Step Create a folder with suitable folder name using ng new folder-name
1:
Step 2 :Open the app.component.html file under src/app folder.
app.component. html
<h1> Demo of Expression </h1>
<h4>Addition of 10 and 20 is:</h4>
{{10+20}}
<br/>
<h4>Addition of two strings '1' and 2' is:</h4>
K{1+2)}
Output
A Expression-App
O localhost4200 A
Demo of Expression
Addition of 10 and 20 is:
30 +
Addition of two strings '1' and '2 is:
12
TECHNICAL PUBLICATIONSan
up-thrust for knowledge
FullStack Web Development 4 - 43 Express and Angular
4.16.1 Pipes
Pipes are used to transform the data. That means pipes take data as input and are getting
transformed into another format. The pipes are written using pipe operator which is denoted by
|. The pipe can be applied to any view or template and to any data input.
Built-in Pipes
1. Lowercase 2. Uppercase
3. Currency 4. Date
5. JSON
Demo Example
Let us understand this with demo example
Step 1:
Create a folder using some suitable name. I have created a folder by a name pipe
demo using the command ng new pipe-demo.
Step 2: Open the app.component.ts file and create a student array as follows -
app.component.ts
import { Component } from '@angular/core;
@Component({
selector: 'app-root,
templateUrl:'/app.component.html,
styleUrls: [/app.component.css]
})
export class AppComponent {
student ={
roll:101,
name:'Anuradha',
city:Pune',
fees:10000,
DOB:09/01/1980'
Step 3: Now open the view page i.e. app.component.html and edit it as follows by using
built in pipes
app.component.html
<h1> Welcome</hl>
<div style="font-weight:bold;">
Name in lower-case: {{student.name lowercase }}
</div>
<divstyle ="font-weight:bold;">
</div>
<div style="font-weight:bold;'>
Date of Birth: {{student.DOB date }}
</div>
Kdiv style-font-weight:bold;'>
Fees: {{student.fees currency:INR}}
</div>
Step 4: Open the command-prompt and issue the command ng serve -0. The output can
be
displayed on the browser windowas follows
A PipeDemo
X
0 localhost4200
A
Welcome
Name in lower-case: anuradha
City in upper-case: PUNE
Date of Birth: Sep 1, 1980
Fees: 10,000.00
Review Questions
1. Explain how to use expressions
in angular ? Give example.
2. What is pipe ? Demonstrate
the code for pipes in Angular.
TECHNICAL
PUBLICATIONS.
an up-thrust
forknowledge
Full Stack Web Development 4 - 45 Express and Angular
Demo example
-
Let us understand this type of binding with the help of example
I have created a folder
Step 1: Now create a workspace folder for the Angular application.
-
binding-demo using ng new command. It is as follows
ng new binding-demo
y css.
The answer to add Angular routing is and stylesheet format is
Step 2 : Now change directory to the binding-demo folder. Go to sre->app folder and open
the file app.component.ts. Add two data member roll no and name to the class
AddComponent
app.component.ts
import { Component } from '@angular/core";
@Component({
selector: 'app-root',
templateUrl: './app.component.html,
styleUrls: [./app.component.css']
})
export class AppComponent {
app.component.html
<h1 style="text-align: center;"> WELCOME</h1>
<h2 style="text-align: center;">Roll no: {{roll no}}</h2>
<h2 style="text-align: center;">Name: {{name}}</h2>
Step 4: Now open the command-prompt window and issue the command ng scrve -o. The
browser window will display the output as follows -
BindingDemo X
:
localhost4200
A
WELCOME
+ Roll no: 101
Name: Anuradha
2) Property binding
The property binding is one-way binding in which we can set the properties of the element
to the user interface page. In this binding [ ] is used for data binding. Following example
illustrates it.
View
Model using
Property
Demo example
Take one image file and save it to src->assets folder. I have with me technical.png file as
a image file which I have saved in src->assets folder.
Step 1: Go to src->app folder and open the file app.component.ts. Add the image variable
as follows -
app.component.ts
import { Component } from '@angular/core':
@Component({
selector:'app-root,
templateUrl: /app.component.html,
styleUrls: [./app.conponent.css']
})
export class AppComponent {
public roll no:number = 101;
public name:String = 'Anuradha':
public image = "/assets/technical.png"
Step 2: Open the app.component.html page and set the property value to image.
app.component.html
<h1>WELCOME</h1>
<h2>Rol no: {{roll no}}</h2>
<h2>Name: {{name}}</h2>
<img (src] = "image alt="Logo' style="height:80px;width:150px>
Step 3: Open the command prompt window and issue the command ng serve -o. The output
-
will be as follows
A BindingDemo
O localhost4200
WELCOME
A
Name: Anuradha
TECHNIGAL
PUBLICATIONS
3) Event binding
case, the event i
The event binding is the flow of data from view to component. In this
component.
triggered on the view or HTML page. The view page sends data to the
View
Model on triggering
triggers event
Event
Script explanation :
Byaboye two steps we have created Enroll button on the HTML nage
and on clicking tne
button, "You are Enrolled" message will be displaved
Step 3: Open the command prompt and issue the command ng serve -o. The output will be
A BindingDemo X
O localhost:4200
WELCOME
Roll n0: 101
Name: Anuradha
Enroll
A BindingDemo
O localhost:4200
localhost:4200 says
A
WE You are now Enrolled!!
OK
+ Roll!
Name: Anuradha
Enroll
Model View
triggers event at the same time
when event gets triggred
@Component({
selector: 'app-root',
templateUrl: '/app.component.html,
styleUrls: [/app.component.css']
app.component.html
<h1>WELCOME</h1>
<h2> Roll no: {{roll no}}</b2>
<h2>Name: ({name}}</h2>
Enter your Comments: <input |(ngModel)]="comment' type=text">
<hr/>
<p>You have entered...</p>
<h4>{{oomment}} </h4>
Script Explanation: Inabove script we have used input textbox,
using ngModel directive
we are binding the contents
of textbox with the variable comment, And below this text box
inside the paragraph element<p> we are interpolating(using
display the contents of the textbox simultaneously as we
{0})
comment the variable to
type it.This illustrates the two-way
binding process.
Step 3: Open the app.module.tsand import
FormsModule to it. In the following code, bold
faced code indicates the modifications
app.module.ts
import { NgModule } from '@angular/core;
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
FullStack Web Development Express and Angular
4-51
import { BrowserModlule } from @angular/platform-browser:
import { FormsModule } from '@angular/forms':
import { AppRoutingMoclule } from'/app-routing.module:
import { Appomponent } from "/app.component':
@NgModule({
[
declarations:
AppComnponent
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
providers: (],
bootstrap: [AppComponent]
A BindingDemo X
O localhost:4200.
WELCOME
+ Roll no: 101
Name: Anuradha
Enter your Comments: Brillant Student!
Brilliant Student!!!
Review Question
binding in Angular.
List and explain various types
of
1.
Demo Example
Step 1: Create a workspace using following command ng new directive-denmo
app.component.ts
import { Component } from 'a@angular/core';
@Component({
selector: 'app-root,
templateUrl: '/app.component.html',
styleUrls: [./app.component.css'|
})
export class AppComponent {
DirectiveDemo X
) localhost:4200
Click to Hide
Welcome user!!
+
DirectiveDemo X
localhost:4200
O
Click to show
A
A
If the expression evaluates to false, then the template for else block is used.
The else binding points to an <ng-template> element labeled #clscBlock. The template
can be defined anywhere in the component view, but is typically placed right after nglf. Let us
understand its usage with the help of example.
Demo Example
@Component({
selector: 'app-root,
templateUrd: "/app.component.html,
styleUrls: [./app.component.css]
TECHNICAL PUBLICATIONS-an
up-thrust for knowledge
Full Stack Web Development Express and Angular
4- 55
A DirectiveDemo X
O localhost4200
Click to Hide
A
Welcome user!!
A
+
Now click the 'Click to Hide' button
A DirectiveDemo X
localhost:4200
Click to show
A
Good-bye!!
A
app.component.ts
import { Component ) from @angular/core'
@Component({
selector: 'app-root',
templateUrl: '/app.component.html,
styleUrls: /app.component.css']
Step 2: Now open the html file and edit the code as follows -
app.component.html
<h1> List of Students </h1>
Ktable border=5>
<th> Roll No</th>
<th>Name</th>
<tr *ngFor="let student of students;">
<td>{{student.roll no}}</td>
<td>{{student.name}}</td>
</tr>
K/table>
Step 3: Run the above application at the command prompt by issuing
ng serve -0. The web browser will get opened up the command
and the output will be displayed as
follows -
A DirectiveDemo
XX
O localhost4200
List of Students
+ Roll No Name
2 Archana
Chinmaya
Soumya
8 |Swati
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development
4- 57 Express and Angular
4.18.1.3 ngSwitch Directive
The [ngSwitch] directive on a container specifies an expression to match
against.
The expressions for matching are provided by ngSwitchCase directives on views within
the container. The ngSwitchCase is preceded by asterisk or *.
Every view that matches is displayed.
If there are no matches, a view with the ngSwitch Default directive is rendered.
Demo example
Let us see the example that explains the use of ngSwitch directive.
Step 1: Go to the folder location in which the application for ngSwitch is to be created.
Step 2: Open app.component.ts file and edit is as follows -
app.component.ts
import Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl:'/app.component.html,
styleUrls: /app.component.oss']
counter=3;
as follows -
Step 3 Now open the html file and edit the code
:
app.component.html
<h3> ngSwitch Demo</h3>
<div [ngSwitch]="counter">
<div *ngSwitchCase="1"> 1 is selected</div>
<div *ngSwitchCase="2"> 2 is selected</div>
<div *ngSwitchCase="3'> is selected</div>
3
A DirectiveDemo X
localhost:4200
ngSwitch Demo
A 3 is selected
Now if we set counter =99 in the app.component.ts file then the output will be
DirectiveDemo X
O localhost:4200 :
ngSwitch Demo
A
Default value
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development 4
-59 Express and Angular
Many ngModules such as the FormsModule define their own attribute directives. The most
common attribute directives are as follows :
Directive Description
ngModel The ngModel directive binds the value changes in the attached form element with
changes in the data model. Thus we can use ngModel to create two-way data
bindings for reading and writing input-control values.
ngForm The ngForm directive creates a top-level FormGroup instance and binds it to a
<form> element to track aggregated form value and validation status. As sOon as we
import FormsModule, this directive becomes active by default on all <form> tags.
There is no need to add a special selector.
ngStyle This directive updates the style of an HTML element.
Demo example
Step 1: Create a new application by creating a folder using following command
ng new form-demo
Step 2 When we want to use the template form, the first thing which we need to do is to
:
as follows -
import FormModule. Open app.module.ts file and import FormModule
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser;
import {FormsModule }
from @angular/forms;
@NgModule({
[
declarations:
AppComponent
[
imports:
BrowserModule,
FormsModule,
AppRoutingModule
providers: []l,
bootstrap: (AppComponent]
})
export class AppModule {}
Step 3 :
We will write code for creating a form with ngModel. so add following code lo
app.component.html file.
app.component.html
<form #myForm='ngForm (ngSubmit)="submit(myForm.value)">
<div class="form-group">
<label for="firstName">First Name <label>
<input type =text' name="frstName" I(ngModel)] ="irstName" >
</div>
<br>
<div class="form-group">
<label for="lastName">Last Name <label>
<input type =text" name="lastName" I(ngModel)] ="lastNamne" >
</div>
<br>
<div class="form-group'>
<label for="mobileNum">Mobile Number <Mabel>
<input type ="text name="mobileNum" [(ngModel)]="mobileNum" >
</div>
<br> <br>
<button type="submit>Submit Kbutton>
</form>
:
Script explanation
In above code we have created three text boxes and one submit button. On submit button,
we call a method named submit(myForm.value). This method
will display the contents
entered by the user in the input text boxes.
The form-group class is used for each component because encourages proper grouping of
labels, controls, optional help text and form validation messaging.
For cach fieldthe ngModel is specified. The ngModel is a directive which binds input,
select and textarea and stores the required user value in a variable and we can use that variable
whenever we require that value.
Step 4 :
In ts file. we will write submit) and get all input fields values. So let's add following
code to app.component.ts file.
app.component.ts
import { Component } fron @angular/core';
@Component({
selector: 'app-root,
templateUrl: /app.component.htm!,
styleUrls: [./app.component.css']
})
export class AppComponent
firstNamne:string =";
lastName:string =";
mobileNum:string =":
submit(form:any) {
Script explanation:
We have defined the variables for form fields and also defined the submit() method, which
was invoked by the form in app.component.html file.(Just refer step 2)
In the submit) method we are retrieving form field values such as First Name, Last Name
and mobile Number and then displaying them using alert popup box.
Step 5: Execute the above application using ng serve -o command at the command-prompt
or terminal window.
The output can be displayed on the browser as follows when we enter some data in the
form fields.
Output
A FomOenmo
O localhost 420
Submt
Review Questions
1. List andeyplain diferent types structural directives in Angular.
of
5. Support for 0OP : The TypeScript can make use of various features of object-oriented
programming languages such as classes. interfaces. inheritance and so on.
Q.4 What is the difference between let and var ?
Ans. : Var declarations are globally scoped or function / locally scoped. The scope is global
when a var variable is declared outside a function. This means that any variable that is declared
-
with var outside a function block is available for use in the whole window. For example
for (var i= 0; i< 5; i+ +) {
console.log("i=", i):
only exists and can be accessible inside the for loop block.
-
For example
for (let i = 0;i< 5; i++){
console.log('i= ", );
Example
class Person {
person id: number;
person name: string:
getName:string {
return "Parth":
console.log("Welcome");
Syntax
(larg1,arg2,., argN]) => expression { //function bodý
By the use of=> arOW we need not have to use the keyword function
For example -
let addtion = (a:number,, b:number):number =>
return a+b;
console.log(addtion(10,20):
Q.9 What is Angular ?
Ans. : Angular is a typescript based free and open source web application framework led by the
Angular team at Google and by a community of individuals and corporations.
Angular 10+ is a JavaScript framework which is used to create Single Page Applications(SPAs).
Q.10 What is the use of ngModule in Angular ?
:
Ans.
Angular modules consolidate components, directives and pipes into cohesive blocks of
functionality.
For defining the module we use the ngModule.
Every Angular application has at least one NgModule class, the root module, which is
conventionally named AppModule and resides in a file named app.module. ts.
Q,11 What are the two types of data bindings in Angular ?
-
Ans.:There are two types of data bindings
1. Property binding This type of binding allows to pass the interpolated values from
:
application data to HTML. The interpolated values are specified in {{ and}} bracket
pair. For instance - the student.name is interpolating value.
<p>Name.: ({ student.name}}</p>
2. Event binding :
Event binding is used to capture events on the user's end on the app
and respond to it in the target environment by updating the application data.
Notes
5 React
Syllabus
MERN STACK - Basic React applications - React Components - React State - Express REST APIs
Modularization and Webpack - Routing with React Router - Server-side rendering
Contents
5.1 MERN Stack
5.2 Basic React Applications
5.3 React Components
5.4 Inter Components Communication
5.5 The props
5.6 React State
5.7 Express RESTAPIs
5.8 Modularization and Webpack
5.9 Routing with React Router
5.10 Server-side Rendering
5.11 Two Marks Questions with Answers
Full Stack Web Development
5-2 React
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development React
5-3
Review Question
1. With suitable block diagram explain the concept
of MERN stack.
5.2 Basic React Applications
Let us start the introduction of ReactUS with a real-world example. Suppose that on a Facebook
page, you click the "ike on some photograph and then by the time you
scroll down the same
page, the like count gets incremented by some number, even
without reloading your Facebook
page. This magic change happens because of our ReactJS!!!
Features of ReactJS
Virtual DOM:DOM stands for Document Object Model. It also provides a way to update
the content, structure and style of the document. Virtual DOM is a representation of original
DOM. When user updates something on the web application, DOM gets updated. Updating
the DOM is very slow, most of the JavaScript frameworks update the whole DOM which
makes it slower. But actually there is no need to update the whole DOM, instead, these
frameworks should update only the part of DOM that is required to update. This is what the
virtual DOM does. This is why ReactJS's DOM manipulation is much faster than other
frameworks. Due to this property, whenever any change is made in the web application, then
those changes are reflected on the web page within no time.
Components : This feature allows the web developer to create custom elements which can
be reused in HTML.
JSX : JSX is an extension of JavaScript syntax. JSX can be seen as a combination of
javascript and XML. The syntax of JSX is very simple that makes writing components very
easy.
.One way data binding : The ReactJS is designed in such a way that it follows.
unidirectional or one way data binding. That means, data is allowed to flow in one direction
at a time., This helps in achieving greater control over the application. This makes helps in
increasing the efficiency of an application.
Installation of ReactJS
Open the command prompt window and issue the command
C:\Users\DELL>npm install -g create-react-app
The installation process will get started. Following screenshot shows it.
os. npm X
C:\Users\DELL>Create-react-app --version
5.0.0
C:\Users\DELL>
That all, if it shows some version number then the reactjs is installed.
npm X
D:\reactDemo>create-react-app firstapp
Creating a new React app in D:\reactDemo\firstapp.
-
Step 2: Now locate the index.js file which is present inside the src folder. Edit it as follows
index.js
import React from 'react';
import ReactDOM from react-dom';
ReactDOM.render(
<h1> Welcome, user!!</h1>,
document.getElementByld('root')
Step 3: Now open the terminal window or command-prompt window and issue the command
npm start
By this command the web browser gets opened and the output will be displayed.
9 React App X
localhost:3000
Welcome, user!!!
+
Review Questions
1. Functional Components
2. Class Component
1. Functional components
Functional components are simple JavaSeript functions. The functional components return the
JSX(JavaScript XML)code to render the DOM tree. Following code fragment shows the functional
component
function Welcome(props) {
return <h1>Welcome {props.name) </h1>;
-
as follows
Alternatively the functional component can be created using arrow function
const Welcome = (props) =>{
return <h1>Welcome (props.name)</h1>;
Note that the function name always start with capital letter.
Demo Example
Step 1: Open the command prompt and issue the following command
D:\reactDemo> create-react-app funcomponent
By this command we are creating a workspace by the name funcomponent in which we will be
creating our function component.
function DisplayStudent(student){
retun <div>
<h2>Student Information....</h2>
<p>
<label>Roll no:<b>{student.Rol}</b></label>
</p>
<p>
<label>Name:<b>{student.Name}</b></label> Here the functional
</p> component is defined.
<p>
<label>phone:<b>{student.Phone} </b><Mabel>
</p> Passing the values to the
</div>; functional component
9 React App X
localhost:3000
O
Student Information...
Roll_no:111
+
Name:Chitra
phone:1234567890
2. Class component
To define the class component we have to first create a class and extend React.Componcnt
class.
Class components are ES6 classes that return JSX. Below, is a class component which is similar
to Welcome function(as given in Functional component) :
Note that the class component must have the render) methodfor returning JSX.
Demo Example
Step 1: Open the command prompt and issue the following command
D:\reactDemo> create-react-app classcomponent
By this command we are creating a workspace by the name classcomponent in which we will
be creating our function component.
Step 2: Locate index.js file in the src folder of your application and edit it as follows
index.js
import React from react':
import ReactDOM fom 'react-dom';
import'/index.css':
class Student extends React.Component
render(){
returm <div>
<h2>Student Information...<h2>
<p>
<label>Roll no:<b>{this.props.Roll}</b></label>
</p>
<p>
<label>Name: <b>{this.props.Name}</b></label>
</p>
<p>
<label>phone:<b>{this.props.Phone}</b></label>
</p>
</div>
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development
5-9 React
:
Step 3 Open the terminal window or command-prompt. Switch to
funcomponent folder and
issue the command npm start. The web browser
willget opened up automatically
and the output will be displayed as follows -
9 React App X
:
O localhost:3000
Student Information...
Roll_no:111
+
Name:Chitra
phone:1234567890
2. These are plain JavaSeript functions that These are the classes that gets extended
accept props as an argument and return from React.Component.
React element.
3. There is no need to use render) method. It must have render() method returning
HTML.
5. Functional components generally are just Class components are used as container
used for display purp0ses. These components to handle state management
Components are used to handle user and wrap child components.
interactions or state updates.
Review Questions
1. Explain the functional component in React.
Step 1 : Go to the directory in which the first application is to be created. At the command
prompt issue the command create-react-app <folder-name>
Step 2: Now open the corresponding folder and edit the index.js file as follows
index.js
import React from 'teact':
import ReactDOM from teact-dom;
class Student extends React.Component{
constructor(props){
super(props):
render(){
return <div>
<h2>Student Information....</h2>
<p>
<label>Roll no:<b>{this.props.RolI}<{b></label>
</p>
<p>
<label>Name: <b>{this.props.Name} </b></label>
</p>
<p>
<label>phone:<b>{this.props.Phone}</b></label>
</p>
<p>
<label>Total Marks:<b>{this.props.Marks) </b></label>
</p>
<Marks English={this.props.Engish} Maths={this.props.Maths}
Science={this.props.Science}></Marks>
</div>
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 5-11 React
class Marks extends React.Component{
constructor(props){
super(props);
render(){
return <div>
ch3>Marks of Each Subject are..</h3>
<p>
<label>English:<b>{this.props.English} </b></Mabel>
</p>
<p>
<label> Maths:<b>{this.props.Maths}</b></label>
</p>
<p>
<label>Science:<b>{this.props.Science) <b></label>
</p>
</div>
const element =<Student Roll="111" Name = "Chitra" Phone = "1234567890* Marks ="95
English="40" Maths="35" Science="20> </Student>
ReactDOM.render(element,document.getElementByld(root));
Step 3:
Open the terminal window and issue the command npm start. The web browser will
get opened up automatically and the output will be displayed as follows -
React App
O localhost3000
Student Information...
Roll _no:111
+
Name:Chitra
phone:1234567890
Total Marks:95
English:40
Maths:35
Science:20
Review Question
1. Write a sinmple React app to demonstrate the communication among 1he components.
The props are basically used to pass data from one component to another.
Demo example
Step 1 :Create a folder with some suitable name. I have created a folder named
statedemo by
the following command
E:> create-react-app statedemo
Step 2: Locate the src folder and edit the index.s file as follows
TECHNICAL PUBLICATIONvS- an
up-thrust for knowledge
Full Stack Web Development 5-13 React
index.js
import React from 'react!:
import ReactDOM frorm 'react-dom';
import './index.css:
class Color extends React.Component {
constructor(props) {
super(props);
this.state = {colomame: "Blue"}:
changeColor()
this.setState({colorname: "Golden"}):
render(){
return (
<div>
<h1>My Favorite Color is {this.state.colorname}</h1>
<button onClick={0=>this.changeColor() } > Click to change color</button>
</div>
Step 3 : Open command prompt and type the command npm start. The output will be
displayed on the web browser
8 React App X
O localhost:3000 A
X
React App +
O localhost:3000
TECHNICAL PUBLICATIONS -
an up-thrust for knowlodge
Full Stack Web Development 5- 15 React
Props allow to pass the data from one State holds the information about the components.
component to another.
Props can be used in both functional as well as State can only be used in class components.
class components.
The parent component sets props for the Event handlers generally update state.
children components
Review Questions
1. Explain the concept of React state with suitable web application.
2. What is the difference between props and states ?
API stands for Application Programming Interface. APIs are a set of functions and
procedures that allow for the creation of applications that access data and features of other
applications, services, or operating systems.
In other words, if you want to interact with a computer or system to retrieve information or
perform a function, an API helps you communicate what you want to that system so it can
understand and fulfil the request.
It is basically software intermediary that allows two applications to talk to each other. For
a
on our mobile phone. we
example -
When we use facebook, send a message or check the weather
ise API.
For example If we want to buy a movie ticket, we go to the online ticket booking site, enter
-
movie name, use credit card infornation, get the ticket, print it. The software that interacts with s
some well known examnlee
to perform all these task is nothing but the API. Following screenshots
of API.
Howyou'llpay
GitHub
VISA DSCOVER
o
Instagram
Facebook
O
Pay with Other
C Google
in Linkedin
Each URL made by the client is a request and data sent back to the
client is treated as response.
The request consists of,
(1)Endpoint
The endpoint (or route) is the URL you request. For example -
http://localhost:8082/
(2) Methods
There are various types of methods. But the most commonly used one are as follows -
1) GET 2) POST 3) DELETE
4) PUT 5) PATCH
These methods are basically used for performing CRUD operations. Here C-
stands for Create,
R- stands for Read, U- stands for Update and D-stands for Delete.
TECHNICAL PUBLICATIONSan
up-thrust for knowedge
Full Stack Web Development 5-17 React
Method Purpose
GET For getting the data from the server, this request is used. The server looks for the
data the client has requested and sends it back to the client.
POST This method is used when new resource is to be created on the server. When
client uses this method and provides the data, then the server createsa new entry
in the database and acknowledges the client whether the creation is successful or
not.
PUT and These are the two methods that are used when the client wants to update some
PATCH resource. When PUT method is used, then that means client wants to update
entire resource. And when PATCH method is used, then that means client simply
wants to update small part of the resource.
There are some software tools such as Postman, that help the client to select the appropriate
method and issue the URL. Following screenshot is of a software tool Postman, using which we
can select appropriate method.
GET http://localhost:8082/employees
GET
COPY
HEAD
OPTIONS
LINK
UNLINK
PURGE
LOCK
(3) Headers
Header are used to provide authentication and other useful information to client and server. The
HTTP headers are property-value pairs separated by Colons(:).
For example -
"Content-Type: application/json"
(4)Data
The DATA contains information which the client wants to send to the server. While sending the
DATA to the server the methods such as POST, PUT, PATCH or DELETE are used.
It is preferred to send the data in JSON format. The format is,
Property1l:value1,
Property2:value2
Request REST
API
Client Using MongoDB
Response Database
Node.js
and Express
Let us understand how to create Node JS REST API with the help of following example
Example Code
Prerequisite : For creating the Node.js Rest APlwe need following software to be instaled in
our machine
1) Postman :
This is an API client. This client software allows us to enter the request in
JSON format and sclect the commands such as GET, POST, UPDATE, DELETE and so
on.
Step 2 : Now open the command prompt window and create package.json file using npm init
command. Following screenshot illustrates the same.
At the command prompt simply type the command
npm init
Then hit the enter button. You can add the values of your choice or simply go on pressing enter
key and accept the default value.
npm
p:VlodeJSExanples\RestApiDenonpa init
This utility will walk you through creating a packoge.json file.
It only covers the nost common itees, and tries to guess sens ible defaults.
See npn help init" for definitive docunentat ion cn these fields
and exactly what they do.
Use 'npa instol1 <pke> afteruards to install a package and
save it as a dependency in the package.json file.
"name": "restapidemo,
"version: "1.9.0,
"description": This is y Rest API Deno Project",
"nain: "app.js,
"scripts: (
1"
"test"
:
Step 3: Now install some more packages that are required for creating this Rest API
Installation of express module
Issue the following command
prompt:>npm install express
TECHNICAL PUBLICATIONS
-
an up-thrust for knowtedgo
Full Stack Web Development 5-20 React
GA. npm
D:\iode)SExamples\RestApiDemo>
D:\Wode)SExamples\RestApiDemo>
Installation of nodemon
Issue the following command at the command
prompt
prompt:>npm install -g nodemon -save-dev
TECHNICAL PUBLICATIONs- an
up-thrust for knowledge
Full Stack Web Development 5-21 React
npm
you have
The sample package.json file will show you all these dependencies of the modules
installed just now
package.json
-
J X
package Notepad
"name": "restapidemo",
"version": "1..0",
"description" "This is my Rest API
:
Demo Project",
"main": "app.js",
"scripts" :: {
"start" "nodemon app.js"
"author": "A.A. Puntambekar",
"license": "ISc",{
"dependencies":
"express": "^4.17.1",
"mongodb": "A3.6.4",
"mongoose": "5.12.0"
Ln 1, Col
1
100% Unix (LF) UTF-8
"start":"nodemon app.js"
your main server in a file named app.js.
Step 4 :Now create
app.js
const express = require('express'):
const mongoose = require('mongoose);
URL for the database
url = 'mongodb://localhost/EmployeeDB'; name
app.use(express.json()
const employeeRouter = require(./routes/employees') //initial endpoint
app.use(/employees,employeeRouter)
app.listen(8082,. () =>{
console.log("Server Started!!")
})
Step 5: Create a folder named routes. Inside the routes folder create a file named
employees.js. This file willhandle the GET and POST requests of REST API. Using
POST request we can create the APl by inserting the data into the database. The GET
request will retrieve and display the data from the database. Thus routing GET
of and
POST requests is done in this file.
employees.js
const express = require(express);
const IOuter = express.Router();
const Employee= require(./models/employee'); This is a router program
that routes on receiving the
particular type of request
rOuter.get('/, async(req,res) =>{
try {
const employees await Employee.find() Handling GET Command
res.json(employees) issued by the client, and using
}
find(), displaying data present
catch(err) { in the Employee database
res.send('Enor is: '+err)
}
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Weh Development 5-23 React
try {
catch(err)
res.send('Error is: '+err)
}
})
module.exports = router
Step 6: Now create another folder named models. Inside models foider create a file named
employce.js. This file will describe the Schema. The fields of the document are
described inthis file along with data type and some other description is mentioned in
this file. Note that the schema is specified in JSON format.
employee.js
const mongoose=require('mongoose')
const employeeschema = new mongoOse.& .Schema( {
name: {
type: String,
Preparing the schema
required: true
for the database
}.
designation: {
type: String,
required: true
})
mongoose.model('Employee,employeeSchema)
module.exports
Step 7 :For better understanding, the folder structure of
this project can be viewed in the
RestApiDemo
models
employee.js
node_modules
routes
employeejs
appjs
package-lockjson
package.json
Step 8: For getting the output, Open the command prompt window and issue the following
command.
DANodeJSExamples\RestApiDemo>nodemon run start
You should get the "Server started" and "Connected to
Database" messages
Command Prompt- nodemon rn start D X
A
D:\Node)SExamples\ResttApiDemonodemon run
nocemon] 2.6.7
start
ocemcor, to
esta: a ay enter rs
Ioodeeor Stting patr(s)
odeo eitg tats0s 5,cjs,7son
nodesor] sting node run start epp.js
(node:13844) iarring: Accessing non-existent -property MongoError
te exports insice circular dependency of nodul
KUse node --trace-Ernings to shod
(node:13844) Deprecatioridarning: current here the warning was created)
Server Discovery and Honitoring en
lgine is depreceted, and ill be resoved
in a future version. To use the ne
Server Discover and onitorig enginE, pass option { useunifiedTopology:
rue } to the MongoCliet constructor. t
Server Started!1!
Cornected to Database
TECHNICAL PUBLUCATIONS-an
up-thrust for knowtedge
Full Stack Web Development
5-25 React
FOST hriptocitont8081fempljees
Send
Parme Attorttion peranet teret ferts Satti Coekla
mdats fom rtenendsd bnr9rntg Bentty
"name: "Anktta".
*desifnatíon': CEO"
Once we hit the send button we get the result by generating the unique id for the data which
we have inserted. It can be viewed as follows,
F Me Hete
Oanebdt nnna
Vsual
*1a: "adcta15stafssa
*dasigattan: "CEO*
4Fd ad bgtca
In this, manner we can insert more data by selecting the Post command. This data is sent to the
app.js server and then getting stored in the MongoDB database.
Inorder to retrieve data being stored, we can use GET method on Postman client and see the
complete data in the form of JSON structure.
14: 04aSStaDal
"deaigatian: ag".
EvckeeDl eoys
Documes hoc
EmployeeDB.employees Vhdsttan
tmdere
Apomgehon Ernlsh Plan
Schem
Documents oPTONS FIND RESET
ADD DATA
te:etlkutt1rem
wirutte1
dexir
sesertlersSNuOSom
employèe details.
manner we have created our REST API for
In this
Review Question
React.js.
Write and explain a simple
application using REST HTTP method APls in
1.
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development React
5-27
module.exports{
entry:Japp/index.js,
Output : After completing all the processes, the React webpack creates a bundle file.
Using output we can specify the name and location of final output file. For example
module.exports ={
entry:'/app/index.js,
output: {
path: path.join( dirname, "/dist"), I/ the bundle output path
filename: "bundle.js", // the name of the bundle
:
Loader Loader is like compiler, it checks for different types of files and match them
with their appropriate loaders for handling them. For example -
module.exports {
module:
loaders:( {
There are certain rules used in the module and those are -
test It checks for particular file type(such as js,.css..jsx and so on)
use It specifies a list of loaders used by any specific file type.
exclude It helps the developer to decide which files should not be processed.
For example -
test:/\.css/.
use:('style-loader,'css-loader]
}
o Plugins :
An eflective plugin intertace is included with Webpack. The majority of
module.exports =!
devServer: {
inline: true,
contentBase:'./dist!,
port: 3O00
}.
}:
Use of Babel
is
Babel is a JavaScript compiler that converts modern JavaScript code into the version which
compatible with all the browsers. Babel transpiles modern JavaScript for use in React Components.
The transpiler is a tool used to convert source code into another source code of same level.
The main reason we need babel in modularization is that it gives us the privilege to make use
of the latest things JavaScript has to offer without worying about whether it will work in the
browser or not.
Demo Example
Step 1: Create a folder with some suitable name. I have created a folder named
webpack_example. Create an index.html file inside it.
Now initialize npm using npm init -y command
npm
init -y
Step 2: Install react and babel packages
Install react
npm ireact react-dom.
Installing babel
npm i D
@babel/core @babel/preset-env @babel/preset-react babel-loader css-loader html
webpack-plugin sass sass-loader style-loader url-Joader webpack webpack-cli webpack-dev-server
webpack.config.js
const path = require'path"');
module.exports {
entry:./app/inde.js',
output: {
path: path.join( dlirname, "/dist"). // the bundie output path
filename: "bundle.js", // the name of the bundle
}.
module:{
rules:
{
test:/^.js$/,
exclude:/(node modules)/.
use:{
loader:babel-loader,
options:{
presets:["@babel/preset-env", "@babel/preset-react"]
}
}.
test:/\.css/,
use:['style-loader'css-loader']
Step 4 :
Create two folders namely app and dist. Inside the app folder create an index.js file.
The entry point must be index.js. The output will be in bundle.js which will be
created by the webpack in the dist folder.
app
JS anotherModule.js
JS indexjs
# mystyle.css
Step 5: Install jqueryusing npm. Following screenshot illustrates this
found vulnerabilities
PS E:\webpack example>
-
Step 6: The source files in app folder are as follows
index.js
import name from JanotherModule.js':
import '/mystyle.css'
import $ from jquery
import React from Teact
import ReactDOM from teact-dom'
<h1>Welcome {name}</h1>
ReactDOM.render(<App/>,document.getElementByld(root')
anotherModule.js
COnst name = Parth'
export default name;
mystyle.css
body {
background: khaki;
h1{
Rcolor:red;
Welcome Parth
l) We have created two js files namely index.js and anotherModule.js and one .css file
named mystyle.css. These are bundled together using webpack module and displayed
the output on the browser.
Review Question
Write a web application of your choice to demonstrate the webpack and
modularization concept.
Router application.
2. React-router-dom :This package enables the user to implement dynamic routing
in a web app.
React Router is the core package for the router. React Router DOM contains DOM bindings
and gives you access to React Router by default.
The React Router API is based on following elements :
<Router:The router that keeps the UIin sync with the URL.
<Link> : Renders a navigation link.
<Route> :
Renders a Ul component depending on the URL.
<BrowserRouter>: It is used for handling the dynamic URL.
Demo example
index.js
welcome.js
Fig. 5.9.1
Step 1 : Create a folder for developing routing application using following command
D:\reactDemo> create-react-app routerdemo
two files
Step 5 :
Locate index.js from src folder. Specify the routes for the above created
welcome.js and contact.js files.
index.js
import React from react;
import ReactDOM from Teact-domn;
import {BrowserRouter, Link, Switch,Route.Routes} from 'react-router-dom';
import Welcome from /welcome';
import Contact from '/contact;
function App(){
return(
<div>
<h1> Router Demo </h1>
<ul>
<i><Link to="/welcomepg>Welcome Page</Link> </i>
<li><Link to="/contactpg'>Contact Page </Link></i>
<ful><Routes>
<Route path="/welcomepg element={<Welcome />} 1>
<Route path=/contactpg element ={<Contact />} />
</Routes>
</div>
ReactDOM.render
<BrowserRouter>
<App></App>
</BrowserRouter>,
document.getElementByld(root
):
Step 6: Open the terminal window and issue the command npm start
React kop
localtyost 3
Router Demo
. WelcoDe Page
+
• Contact Page
o.
O localhost 3000/welco.
Router Demo
• Welcome Page
• Contact Page
Welcome User!!!!
localhost.3000/contac...
Router Demo
Welcome Page
Contact Page
Phone: l234567890
Email:abe.xyz@ gmail.com
Review Question
Explain with suitable application for demonstrating routing with React JS.
The process of utilizing the HTML rendered on the server for a component is called
hydration. The ReactDOM.render) function does not perform hydration but replaces
the entire HTML tree by rendering the component from the scratch. For hydration, we
need to use ReactDOM.hydrate) function.
limport App components
import ( App } fromfcomponents/app;
I/compile App component in #app HTML element
ReactDOM.hydrate(<App/>, document.getElementByld('app) );
This function works exactly the same as the render function but it utilizes
the server-side
rendered HTML instead of rendering the component. However,
it expects the server
side rendered HTML and HTML rendered by the
App component to be exactly the
same. If there is a mismatch, it can lead to
unexpected results.
TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 5-37 React
sending it to the user, the search engines can easily index and crawl it.
.
2) Fast load time The server side rendering improves the speed of page loading
:
This
improves the overall user experience.
3) Indexing with the use of Social media : Client-side rendering is not supported by
Facebook's Open Graph Protocol or Twitter Cards, for example. If social media sharing is
an important part of marketing strategy, server-side rendering may be a better option.
2) Slower page rendering : The Server side rendering is ideal for static HTML site
generation, but for complex applications it may result in slower page rendering.
Review Questions
What is server side rendering? Explain.
2 Give the adhvantages and disacdantages of serverside rendering
3 What is the diference betveen server side rendering and client side rendering.
Facebook.
This library is responsible only for the view layer of the application. That means this
JavaScript is for building user interfaces.
Q.3 What are functional components in ReactJS ?
Ans. : Functional components are simple JavaScript functions. The functional components
return the JSX(JavaScript XML)code to render the DOM tree. Following code
fragment shows
the functional comnponent
function Welcome(props) {
return <h1>Welcome {props.name)</h1>;
TECHNICAL PUBLICATIONS-an
up-hrust for knowledge
Full Stack Web Development 5-39 React
Ans. Webpack in react is a JavaScript module bundler that is commonly used with React to
:
bundle and manage dependencies. The webpack takes all the necessary JavaScript fles, CSS
fles combine them into a single bundle that can be loaded by the browser.
Q.8 What is Babel ?
Ans. Babel is a JavaScript compiler that converts modern JavaScript code into the version
:
which is compatible with all the browsers. Babel transpiles modern JavaScript for use in React
Components. The transpiler is a tool used to convert source code into another source code of
same level.
The main reason we need babel in modularization is that it gives us the privilege to make use
of the latest things JavaScript has to offer without worrying about whether it will work in the
browser or not.
Q.9 What is React Router
a web
Ans. ReactJS router is a single page application. The single page application is
:
application that interacts with the user by dynamically rewriting the current page, rather than
a
loading entire new pages from the server. When a user types specific URL into the browser
and if this URL path matches any 'route' inside the router file, the
user will be redirected to that
particular route.
Q.10 List and explain the packages that are used in ReactJS routing
:
Ans.
1, react-router : It provides core routing components and functions for the React Router
application.
2. React-router-dom : This package enables the user to implement dynamic routing in a web
app.
Q.1 What is web development framework ? (Refer Two Marks Q.1 of Chapter - 1)
Q.3 What is Nodejs ? Give its uses. (Refer Two Marks Q.1 of Chapter - 2)
Q.4 Explain the use of
ClientRequestobject. (Refer Two Marks Q.12 of Chapter - 2)
Q.9 What are functional components in ReacJS ? (Refer Two Marks Q.3of Chapter - 5)
) What are the components of basic web development framework? Explain each.
(Refer section 1.1)
Q.12 a) i) What is Node Package Manager(NP M).
Also explain the command line options
of npm. (Refer section 2.4)
i) What is stream ? Eyplain how to perform read and write operations in Nodejs
using stream. (Refer section 2.10.2) [6]
(M- 1)
Full Stack Web Development M-2 Solved Model Question Paper
OR
b) i) How event listener is handled in Node.js. Explain it with suitable example code.
(Refer section 2.7) [7]
i) Explain any two built-in modules in Node,js. (Refer section 2.4.3) |6]
Q.13 a) ) Elaborate the steps sed for comecting the MongoDB with Node,js
(Refer section 3.8) [5]
OR
b) i) How tocreate an inder and find the index in MongoDB ? Explain it with suitable
example. (Refer section 3.11.1) [5]
ii) Explain the i) MongoDBClient object and i)db object with methods
associated with it. (Refer section 3.9) [8]
Q.14 a) ) Explain the implementation of routing techmique in express with example.
(Refer section 4.2) [8]