WT MOD - 4 (ELECTIVE MBCET NOTES - CT) 23

PerfectOK1 0 views 138 slides Oct 24, 2025
Slide 1
Slide 1 of 138
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138

About This Presentation

Web Technology MBCET Module 4 notes


Slide Content

Node.js Modules, Event Loop, Express.js Routing and Middleware, Form
Handling, Sessions, Cookies, File System Access, Templating with EJS or Pug,
REST API Design, HTTP Methods, Stateless Communication, JSON Parsing
and Serialization, AJAX, Fetch API, MongoDB, Mongoose, Schema Design,
CRUD Operations, Overview of PHP and Python for backend development.
BACKEND DEVELOPMENT, API’S, AND FULL STACK INTEGRATION
1

Node.js
►Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to execute JavaScript code outside of a web browser.
►Built on Chrome's V8 JavaScript engine, it enables the use of JavaScript for server-side and
networking applications, command-line tools, and more.
►Modules handle file system I/O, networking, binary data (buffers), cryptography functions, data
streams, etc.
►Frameworks can be used to accelerate the development of web applications; common frameworks
are Express.js, Koa, Sails.js, Total.js.
►Node.js is not limited to the server-side — it provides a number of tools for frontend development
workflows.
2

Node.js
What Can Node.js Do?
►Web Servers: Create fast, scalable network applications
►File Operations: Read, write, and manage files on the server
►Database Interaction: Work with databases like MongoDB, MySQL, and more
►APIs: Build RESTful services and GraphQL APIs
►Real-time: Handle WebSockets for live applications
►CLI Tools: Create command-line applications
3
Mrs. Bindhya P S, MBCET

4
Mrs. Bindhya P S, MBCET

Node.js Modules
►Modules are the building blocks of Node.js applications, allowing you to organize code into logical,
reusable components. They help in:
►Organizing code into manageable files
►Encapsulating functionality
►Preventing global namespace pollution
►Improving code maintainability and reusability
►A Node.js Module is a library of functions that could be used in a Node.js file.
►Node.js supports two module systems: CommonJS (traditional) and ES Modules (ECMAScript
modules).

5
Mrs. Bindhya P S, MBCET

Node.js Modules
There are three types of modules in Node.js based on their location to access. They are :
Core Modules: These are the modules that come along with Node.js installation.
Third-party Modules: These are external modules developed by the community and can be installed using
npm (Node Package Manager).
Custom Modules: These are the modules written by user or a third party.

6
Mrs. Bindhya P S, MBCET

Core Modules:
►Node.js provides several built-in modules that are compiled into the binary.
►To use any built-in module, use the require() function:
Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.
Calling require() always use the CommonJS module loader.
Calling import() always use the ECMAScript module loader.
7
Mrs. Bindhya P S, MBCET

Core Modules:
►To use any built-in module, use the require() function:
Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.
const http = require('http');
Web server using HTTP module
Web server output
This is what the output looks like on the web browser when we go
to the URL with the correct port.
8
Mrs. Bindhya P S, MBCET

Core Modules:
const url = require('url');

// Our URL
const myURL = 'https://www.example.com:8080/path/to/resource?id=123&name=John%20Doe';

// We parse the Url
const parsedURL = new URL(myURL);

// We print the url components
console.log('Protocol:', parsedURL.protocol);
console.log('Host:', parsedURL.host);
console.log('Pathname:', parsedURL.pathname);
console.log('Query Parameters:', parsedURL.searchParams.toString());

Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.
9
Mrs. Bindhya P S, MBCET

Custom Modules/Local Modules
►To use these modules,
let localModule = require(./localModuleName)
localModule: The variable in which we store the local module.

./localModuleName: The relative path to the JavaScript file that contains the local module.
10
Mrs. Bindhya P S, MBCET

Custom Modules/Local Modules
Calculate.js
function square(number) {
return number * number;
}
function cube(number) {
return number * number * number;
}
module.exports = {
square: square,
cube: cube
};

Index.js
const calculate = require('./calculate');
const num = 5;

const sqNum = calculate.square(num);
console.log("Square of", num, "is:", sqNum);

const cubeNum = calculate.cube(num);
console.log("Cube of", num, "is:", cubeNum);
11
Mrs. Bindhya P S, MBCET

12
1.Create a Node.js application that uses a user-defined module to check whether a given number is
prime or not.
// prime.js
function isPrime(num) {
if (num <= 1)
return false;
for (let i = 2; i <= Math.sqrt(num); i++)
{
if (num % i === 0)
return false;
}
return true;
}
module.exports = isPrime;
// app.js
const isPrime = require('./prime');
const number = 17;
if (isPrime(number))
{
console.log(number , " is not a prime number");
}
else
{
console.log(number, "is not a prime number");
}

13
2.Create a Node.js application that uses a user-defined module to check whether a given string is a
palindrome.
// palindrome.js
function isPalindrome(str)
{
const cleanstr = str.toLowerCase().replace(/[^a-z0-9]/g, ‘ ');
const reversed = cleanstr.split('').reverse().join('');
return cleanstr === reversed;
}
module.exports = isPalindrome;
// app.js
const isPalindrome = require('./palindrome');
const testString = “Malayalam";
if (isPalindrome(testString))
{
console.log(testString, "is a palindrome");
}
else
{
console.log(testString, "is not palindrome");
}

14
3.Create a Node.js application that uses a user-defined module to calculate the sum of all elements in an array.
// sum.js
function arraySum(arr)
{
let sum = 0;
for (let num of arr)
{
sum += num;
}
return sum;
}module.exports = arraySum;
// app.js
const arraySum = require("./sum");
let arr1 = [10, 20, 30, 40];
console.log("Array 1:", arr1, " Sum =", arraySum(arr1));

15
3.Create a Node.js application that uses a user-defined module to calculate the sum of all elements in an array.
// factorial.js
function factorial(n)
{
if (n < 0)
return "Factorial not defined ";
if (n === 0 || n === 1)
return 1;
let fact = 1;
for (let i = 2; i <= n; i++)
{
fact *= i;
}
return fact;
}module.exports = factorial;
// app.js
const prompt = require("prompt-sync")();
const factorial = require("./factorial");
const num = parseInt(prompt("Enter a number: "));
if (isNaN(num) || num < 0)
{
console.log(" Please enter a positive number");
}
else
{
console.log("Factorial of", num, "=", factorial(num));
}

Third-Party Modules:
These modules are created by the community and can be installed using npm (Node Package
Manager).
Examples include:
►express: Web application framework
►mongoose: MongoDB object modeling tool
►lodash: Utility library for working with arrays, numbers, objects, etc.
►The third-party modules in Node.js are those we install globally or on our local machines from external
sources, typically via the Node package manager. To install them using npm, we can use the following
command:
npm install thirdPartyModuleName
Syntax for requiring our local module: let thirdPartyModule = require(thirdPartyModuleName)
16

Third-Party Modules:
►Use the lodash module, which is a third-party module useful in the manipulation of arrays.
►To use this external module, Install it using the following command:
npm install lodash
const calculate = require('lodash'); // Requiring the 'lodash' third-party module

const numbers = [1, 2, 3, 4, 5]; // Sample data

const sum = calculate.sum(numbers); // Using 'lodash' functions

console.log('Sum:', sum); // Output: Sum: 15
17
Mrs. Bindhya P S, MBCET

►Node.js applications
experience four types of
errors.

Error Handling

18
Mrs. Bindhya P S, MBCET

►The Event Loop is essential in Node.js because it allows non-blocking, asynchronous operations to
be handled efficiently, even though Node.js operates on a single thread..
►Allows asynchronous tasks to be handled efficiently without blocking the execution of other
operations. It:
►Executes JavaScript synchronously first and then processes asynchronous operations.
►Delegates heavy tasks like I/O operations, timers, and network requests to the libuv library.
►Ensures smooth execution of multiple operations by queuing and scheduling callbacks efficiently.
►To support the event-loop approach, Node supplies a set of nonblocking I/O modules — these
are interfaces to things such as the filesystem or databases, which operate in an event-driven
way.
Event Loop 19
Mrs. Bindhya P S, MBCET

Example 20
Mrs. Bindhya P S, MBCET
const a = () => console.log('a');
const b = () =>
setTimeout(() =>
console.log('b'), 100);
const c = () => console.log('c');

a();
b();
c();

Call stack
21
Mrs. Bindhya P S, MBCET
•JavaScript can do one single thing at a time because it has only one call stack.
•It follows LIFO(Last in first out).
•The call stack is a mechanism that helps the JavaScript interpreter to keep track of the functions that a
script calls.
•Every time a script or function calls a function, it's added to the top of the call stack. Every time the
function exits, the interpreter removes it from the call stack.
Web API/C++ API:
•web API or C++ API is the assistant of the call stack.
•It helps to execute asynchronous task run concurrently.

Callback Queue:
22
Mrs. Bindhya P S, MBCET
•It follows FIFO(First In First Out).
•An asynchronous operation, such as a timer or an API request, is completed or an event is triggered, the
corresponding callback function is placed in the callback queue.
Event Loop:
•The event loop is a loop that continuously checks the state of the call stack and the event queue.
•If the call stack is empty, the event loop takes the first callback from the event queue and pushes it onto the
call stack for execution.

23
https://dev.to/nodedoctors/an-animated-guide-to-nodejs-event-loop-3g62

24
Synchronous Functions Asynchronous Functions
Blocks the execution until the task completes.
Does not block the execution; allows other tasks to proceed
concurrently.
Executes tasks sequentially; each task must be completed
before the next one starts.
Initiate tasks and proceed with other operations while waiting
for completion.
Returns the result immediately after completion.
Typically returns a promise or callback or uses event handling
to handle the result upon completion.
Errors can be easily caught with try-catch blocks.
Error handling is more complex and often involves callbacks,
promises, or async/await syntax.
Suitable for simple, sequential tasks with predictable
execution flow.
Ideal for I/O-bound operations, network requests, and tasks
requiring parallel processing.

25
Node.js is a JavaScript runtime environment.
Express is the framework written for Node.js.

What is Express.js?
►Express.js is a web application framework for Node.js. Its main goal
is to simplify the building of web applications and APIs.
►Although Node.js can handle HTTP requests by itself, the process can
be quite complicated.
►Express.js simplifies this process by providing a high-level application
programming interface (API) that makes it easy to manage routes,
requests, responses, and middleware handling.
26

Installing Express
►The Express.js package is available on npm package repository.
►Install express package locally in an application folder named ExpressApp.
27
D:\expressApp> npm init -y
D:\expressApp> npm install express --save
This installs the ExpressJS framework and adds it to the dependencies section of your
package.json.

create a file - server.js
const express = require('express'); // Import Express
const app = express();
const PORT = 3000;
app.get('/', (req, res) => { // Define a route
res.send('Hello, Express JS here');});
app.listen(PORT, () => { // Start the server
console.log(`Server is listening at http://localhost:${PORT}`);});
Create a Basic Express Server 28
Run your server with the following command:
node server.js

Express.js Routing
►Routing refers to how an application responds to client requests to specific endpoints
(URIs) using different HTTP methods (GET, POST, PUT, DELETE, etc.).
Routing in Express follows a basic pattern:
app.METHOD(PATH, HANDLER);
29


•METHOD: HTTP methods- GET, POST, PUT, DELETE, etc.

•PATH: URL/endpoint where the handler runs.

•HANDLER: Function called when the request matches.
Routes are defined using methods like app.get(), app.post(), etc.

Express.js Routing
Express provides simple methods to define routes that correspond to HTTP
methods:
▪ app.get() - Fetch data (like visiting a webpage).
▪ app.post() - Submit new data (like filling a form).
▪ app.put() - Update data (like editing profile info).
▪ app.delete() - Remove data (like deleting an account).
▪ app.all() - Catch everything at a path (used for debugging, middleware, or handling errors).


30

31
const express = require('express');
const app = express();

// GET route
app.get('/', (req, res) => {
res.send('Welcome to Express Routing!');});

// POST route
app.post('/submit', (req, res) => {
res.send('Form Submitted Successfully!');});

// PUT route
app.put('/update', (req, res) => {
res.send('Resource Updated!');});
// DELETE route
app.delete('/delete', (req, res) => {
res.send('Resource Deleted!');});

// ALL methods route
app.all('/test', (req, res) => {
res.send("This route handles any HTTP
method!");});

// Start server
app.listen(3000, () => {
console.log('Server running on port 3000');});

32
•Request Object − HTTP request and has properties for the request query
string, parameters, body, HTTP headers, and so on.
•Response Object − The response object represents the HTTP response that an
Express app sends when it gets an HTTP request.
•send() method of the response object formulates the server's response to the
client.

•PUT, POST, DELETE routes can't be triggered by directly entering a URL in the
browser address bar—the browser only sends GET requests this way.
•Tools like Postman or fetch/AJAX are needed to send PUT requests.

GET method
The response object also has a sendFile() method that sends the contents of a given file as the
response.
res.sendFile(path)
Example: index.html in the root folder of the express app.
<html>
<body>
<h2 style="text-align: center;">Hello World</h2>
</body>
</html>
33

GET method
Example: index.js in the root folder of the express app.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,"index.html"));
})
var server = app.listen(5000, function () {
console.log("Express App running at http://127.0.0.1:5000/");
})
34

Middleware in Express
Middleware functions are the backbone of Express applications.
They have access to:
► The request object (req)
► The response object (res)
► The next middleware function in the stack (next)
35
Built-in Middleware
• express.json() - Parse JSON request bodies
• express.urlencoded() - Parse URL-encoded request bodies
• express.static() - Serve static files
• express.Router() - Create modular route handlers

Middleware in Express.js
►Middleware refers to software that lies between the application and the server to
communicate with each other. Ie, it works in the middle to deliver services to applications.
►Middleware functions are executed in the order they are defined. They can perform tasks like
authentication, logging, or error handling.

36
The basic pattern of middleware in Express.js
var app = express();
// This middleware function is called every time a request comes for any route.
app.use(function (req, res, next) {
// body of middleware function.
next();
})

How Middleware Works in Express.js?

37
1.Request arrives at the server.
2.Middleware functions are applied to the request, one by one.
3.Each middleware can either:
•Send a response and end the request-response cycle.
•Call next() to pass control to the next middleware.
4.If no middleware ends the cycle, the route handler is reached, and a final response is sent.
A route handler is the final function that sends a response to the client for a given HTTP request.

A Simple Middleware Chain

const express = require('express');
const app = express();
// First middleware
app.use((req, res, next) => {
console.log('Middleware 1 always runs');
next();
});

// Second middleware
app.use((req, res, next) => {
console.log('Middleware 2 always runs');
next();
});

38
// Route handler
app.get('/', (req, res) => {
res.send('Hello World!');
});

// Start the server
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Types of Middleware
►Application-level middleware: Applied to all requests in an Express application using
app.use().
►Router-level middleware: Applied to specific routes or a group of routes using
router.use().
►Built-in middleware: Provided by Express itself (e.g., express.static, express.json,
express.urlencoded).
►Third-party middleware: External libraries designed to work with Express (e.g., morgan
for logging, helmet for security, cors for cross-origin resource sharing).
►Error-handling middleware: Special middleware functions with four arguments (err,
req, res, next) specifically designed to handle errors.
39

How Middleware Works in Express.js?

40
const express = require('express')
const app = express()

// App level middleware
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
Application-level middleware

Router-level middleware

41
const router = express.Router();

// Router-level middleware
router.use((req, res, next) => {
console.log('This middleware runs for routes defined by the router.');
next();
});

// Mount the router at a specific path
app.use('/myapp', router);

Error-handling middleware

42
Error-handling middleware always takes four arguments.
err: The error object.
req: The request object.
res: The response object.
next: The next middleware function.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

Built-in middleware:-
43
•Built-in middleware are middleware functions that are included with the Express framework by default.
app.use(express.static('public'));
app.use(express.json());
• express.json(): Parse JSON request bodies
• express.urlencoded(): Parse URL-encoded request bodies
• express.static(): Serve static files
• express.Router(): Create modular route handlers
Third-party Middleware
• Helmet: Secure your app by setting various HTTP headers
• Morgan: HTTP request logger
• CORS: Enable CORS with various options
• Compression: Compress HTTP responses
• Cookie-parser: Parse Cookie header and populate req.cookies
const morgan = require('morgan');
const helmet = require('helmet');

// HTTP request logger
app.use(morgan('dev'));

// Security headers
app.use(helmet());

Form Handling
►Form handling in Express.js involves receiving, processing, and responding to data
submitted through HTML forms.
44
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded form data
app.use(express.json());
app.get('/', (req, res) => { // Route to serve a simple form
res.send(` <form action="/submit" method="post">
<input type="text" name="username" placeholder="Enter username" />
<input type="password" name="password" placeholder="Enter password" />
<button type="submit">Submit</button>
</form> `);});
app.post('/submit', (req, res) => {
console.log('Form data:', req.body);
res.send(`Received form data: ${JSON.stringify(req.body)}`);
});
app.listen(3000, () => { console.log('Server running at http://localhost:3000');});

Sessions
►Sessions in Express.js are a mechanism for maintaining stateful interactions between a
client and a server over the stateless HTTP protocol.
►They allow the server to remember user-specific data across multiple requests, which is
crucial for features like user authentication, personalized content, and shopping carts.
►Installation: Install the express-session middleware:
npm install express-session
45

Sessions
const express = require("express");
const session = require("express-session");
const app = express();
// Configure session middleware
app.use(session({
secret: "mySecretKey",
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
46
// Example route
app.get("/", (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`You visited this page
${req.session.views} times`);
} else {
req.session.views = 1;
res.send("Welcome! Refresh the page to
count visits.");
}
});

app.listen(3000, () => {
console.log("Server running on
http://localhost:3000");
});

Cookies
Cookies in Express.js are small pieces of data sent from a server to a client and stored
by the client's web browser.
47
The main issue with a cookie is that it is accessible via the browser.

Cookies
►Cookies are small pieces of data stored on the
client’s browser to identify users.
►Sessions store user data on the server, and only the
session ID is shared with the client through cookies.
►When the client first visits, the server creates a
session and sends the session ID as a cookie.
►On later visits, the client sends back the cookie (with
session ID), so the server can fetch the correct user
data.
►This approach keeps sensitive information safe on
the server while using cookies only for identification.
48

Cookies in Express:
►To use cookies in Express, install the cookie-parser package, It is a
middleware that is used to parse cookies from the incoming request.


►To use cookies with Express, requires the cookie-parser. cookie-parser is a
middleware which parses cookies attached to the client request object
49
npm install cookie-parser
var cookieParser = require('cookie-parser');
app.use(cookieParser());

Cookies in Express: 50
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

app.get('/setCookie', (req, res) => {
res.cookie('username', ‘XYZ').send('Cookie set');
});

app.get('/getCookie', (req, res) => {
res.send(req.cookies.username);
});

app.get('/clearCookie', (req, res) => {
res.clearCookie('username').send('Cookie
deleted');
});

app.listen(3000);

Cookies in Express: 51
Session Cookies
A session is stored at server side A cookie is stored at client side
It can store a data ranging between 5mb - 10mb It can only store a data of 4kb
It is destroyed when user logout.
It is destroyed when user closes the page or it will
remain until the defined time.
express-session middleware is required to create a
session.
It doesn't require any middleware to create a cookie.
Express provide built in support.
Session id is used as a identifier. Key-value pair data is used as a identifier.
The performance of session is slower due to server
interaction.
The performance of cookie is faster, as data is
stored locally.
It is more secure as data are stored at server side.It is less secure as data are stored at client side.
It is used for storing user-specific data. It is used to store user preference data.

File System Access 52
•Express.js itself does not provide file system APIs but easily integrates with Node.js’
built-in fs (File System) module to perform file read/write operations alongside handling
HTTP requests.
To read a file in an
Express route:
const fs = require('fs');
app.get('/read', (req, res) => {
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
return res.status(500).send('Error reading file');
}
res.send(data);
}); });

File System Access 53
Common fs Operations with Express

fs.readFile() – Read contents of a file asynchronously.

fs.writeFile() – Write or overwrite data in a file asynchronously.

fs.appendFile() – Add data to the end of a file.

fs.readdir() – Get a list of files in a directory.

fs.unlink() – Delete a file.

fs.mkdir() / fs.rmdir() – Create or remove directories.

54
//filesystem.js
const express = require("express");
const fs = require("fs");
const app = express();
const port = 3000;

// Route: Write to a file
app.get("/write", (req, res) => {
fs.writeFile(“file.txt", "Hello, this is written by Express.js!", (err) => {
if (err) {
return res.status(500).send("Error writing to file.");
}
res.send("File created and text written successfully!");
});});

// Route: Read a file
app.get("/read", (req, res) => {
fs.readFile(“file.txt", "utf8", (err, data) => {
if (err) {
return res.status(500).send("Error reading file.");
}
res.send(`File contents: ${data}`); });});

55
// Route: Append to a file
app.get("/append", (req, res) => {
fs.appendFile(“file.txt", "\nThis line was appended!", (err) => {
if (err) {
return res.status(500).send("Error appending to file.");
}
res.send("Text appended successfully!");
});
});

// Route: Delete a file
app.get("/delete", (req, res) => {
fs.unlink(“file.txt", (err) => {
if (err) {
return res.status(500).send("Error deleting file.");
}
res.send("File deleted successfully!");
});
});

56
// Home route

app.get("/", (req, res) => {
res.send(` <h1>File System Access with Express.js</h1>
<ul>
<li><a href="/write">Write File</a></li>
<li><a href="/read">Read File</a></li>
<li><a href="/append">Append to File</a></li>
<li><a href="/delete">Delete File</a></li>
</ul> `);
});

// Start server

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Run the app: node filesystem.js

Open browser and visit:
Open browser and visit:
http://localhost:3000/write
http://localhost:3000/read
http://localhost:3000/append
http://localhost:3000/delete

Creating directories.
fs.mkdir('path/to/new/directory', { recursive: true }, (err) => {
if (err) {
console.error(err);
return;
}
console.log('Directory created successfully!');
});
57

Templating with EJS or Pug
►EJS (Embedded JavaScript) and Pug (formerly Jade) are popular
templating engines used with Node.js to generate dynamic HTML content.
EJS (Embedded JavaScript)

58
•Fast compilation and rendering
•Simple template tags: <% %>
•Custom delimiters (e.g., use [? ?] instead of <% %>)
•Both server JS and browser support
•Static caching of intermediate JavaScript
•Static caching of templates
•Complies with the Express view system

Templating with EJS 59
EJS is a web template engine that generate
HTML documents by embedding
JavaScript code snippets within HTML
code.
Install EJS to the project: npm install ejs
EJS files are saved with the .ejs file extension

60
// server.js
const ejs = require('ejs');
const template = `
<h2>Hello <%= name %>!</h2>
<p>Today is <%= date %></p>
<p>1 + 2 is <%= 1 + 2 %></p>
`;
const data = {
name: 'John',
date: new Date().toISOString().split('T')[0]
};
const output = ejs.render(template, data);
console.log(output);
EJS code looks like pure HTML.
It retains the syntax of HTML while allowing data
interpolation

How to set up EJS in a Node.js application using
Express

►Install : npm install express ejs
►After installation, create a app.js file and a views directory in the root project directory.
Inside the views directory, create two directories — pages and partials.
61
//app.js
const express = require('express');
const app = express();
const port = 3000;

// setup view engine
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
res.render('pages/index');
});

app.listen(port, () => {
console.log(`App listening at port ${port}`);
});

How to set up EJS in a Node.js application using
Express

►Inside the views/pages directory, create a file called index.ejs
62
//index.ejs
<html>
<body>
<h1>Hi, there!</h1>
</body>
</html>
inside the views/pages directory, create a file called index.ejs

EJS lets you embed JavaScript directly inside your HTML.
<% %> → Run JavaScript code (no output)

<%= %> → Output the result (escaped)
<%= "<b>Hello</b>" %> Output: <b>Hello</b> (just text, not bold)

<%- %> → Output unescaped (raw HTML)
<%- "<b>Hello</b>" %> Output: Hello
63
<% if (user.age >= 18) { %>
<p><%= user.name %> is an adult.</p>
<% } else { %>
<p><%= user.name %> is a minor.</p>
<% } %>

Creating reusable views with EJS partials

►Some parts of websites stay the same across different pages, like the header, footer, and
sidebar.
►EJS lets you create shared templates and import them with the include(file) inbuilt function.
►Create two new files named header.ejs and footer.ejs in views/partials.
64

Pug
►Pug (formerly Jade) is a templating engine like EJS, but it uses indentation instead of HTML tags.
►Install: npm install express pug
►Pug uses indentation instead of closing tags.
►= is used to output variables.
65

REST API Design
►An application programming interface (API) is a mechanism that allows an application or
service to access a resource within another application or service. It defines the rules to
communicate with other software systems.
►The common API standard used by most mobile and web applications to talk to the servers is called
REST. It stands for REpresentational State Transfer.
►REST is an architectural design style for APIs, while HTTP is the communication protocol used for
data transfer over the web.
►REST APIs use HTTP methods to interact with resources.
►REST defines how the APIs should behave, while HTTP defines the rules for communication over
the web. They commonly work together, but they serve different purposes.
►REST APIs usually send static resources.
66

REST API Design
►A request is sent from the client to the server via a web URL, using one of the HTTP methods.
►The server then responds with the requested resource, which could be HTML, XML, Image, PHP,
Plaintext or JSON. JSON is the most popular file format .
►These methods map to CRUD operations (Create, Read, Update, Delete) for managing resources
on the web.
67

HTTP Methods in RESTful API
services
68
An HTTP method tells the server what it needs to do to the resource. The following are four
common HTTP methods:
►GET : Clients use GET to access resources that are located at the specified URL on the server.
►POST: Clients use POST to send data to the server.
►PUT: Clients use PUT to update existing resources on the server.
►DELETE : Clients use the DELETE request to remove the resource. A DELETE request can
change the server state.
Responses from the server contain status codes to alert the client to information about the success
of the operation.
►GET — return 200 (OK)
►POST — return 201 (CREATED)
►PUT — return 200 (OK)
►DELETE — return 204 (NO CONTENT)




The status line contains a three-digit status code that
communicates request success or failure.
For instance,
2XX codes indicate success,
but 4XX and 5XX codes indicate errors.
3XX codes indicate URL redirection.

HTTP Methods in RESTful API
services
69

Principles of REST Design
►REST APIs can be developed using any programming language and support various data
formats.
►The six REST design principles, or architectural constraints, are
►Uniform Identifier (URI)
►Client-Server Independence
►Request Information Inclusion
►Caching
►Layered System
►Code-on-Demand (Optional)
70

Statelessness
►In REST architecture, statelessness refers to a communication method in
which the server completes every client request independently of all
previous requests.
►Clients can request resources in any order, and every request is stateless or isolated from
other requests.
►This REST API design constraint implies that the server can completely understand and
fulfill the request every time.
►RESTful web services support caching, which is the process of storing some responses on
the client or on an intermediary to improve server response time.
71

JSON
72
►JSON (JavaScript Object Notation) is a lightweight data-interchange format.
►It is human-readable and easy for machines to parse and generate.
►JSON is widely used for data exchange between a client and a server in web
applications, as well as for storing data in various systems
►JSON data is represented as key-value pairs, similar to a dictionary or a hash
table.

JSON Parsing
73
▪JSON parsing also known as deserialization, is the process of converting a
JSON string into a structured data object within a programming language.
▪This allows the program to access and manipulate the data contained within the
JSON.
import json
json_string = '{"name": "Alice", "age": 30, "city": "New York"}‘
data = json.loads(json_string) # Parses the JSON string into a Python dictionary
print(data["name"]) # Output: Alice
print(data["age"]) # Output: 30

Example of a JSON object that represents a person
74

JSON
75
Three components of JSON
► JSON Object - A JSON object is an unordered collection of key-value pairs,
where the keys are strings and the values can be any valid JSON data type
enclosed in curly braces { }.
► Key and values (JSON Data type)- The keys are always strings, followed by
a colon, and the values can be any valid JSON data type such as strings,
numbers, Boolean, arrays or objects.
►JSON array - A JSON array is an ordered list of values enclosed in square
brackets [ ]

CRUD Operations
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

// GET requests
app.get('/users', (req, res) => {
res.json({ message: 'Returning list of users' });
});

76
// Output : GET

CRUD Operations
// POST requests
app.post('/users', (req, res) => {
const newUser = req.body;
res.json({ message: 'User created', user: newUser });
});

77
// Output : created JSON
// Output: POST Request

CRUD Operations
// PUT requests
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
res.json({ message: `User with ID ${userId} updated`, updatedUser });
});

78
// Output : Updated JSON id: name
// Output: POST Request

CRUD Operations
// DELETE requests
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ message: `User with ID ${userId} deleted` });
});
app.listen(port);

79
// Output : Updated JSON id: username
// Output: DELETE Request

JSON Serialization:
80
•JSON is a data format used to serialize data.
•Serialization is the process of converting a data object that exists in computer memory into a
series of bytes that can be easily persisted or transmitted.
•Serialized data can be stored on disk, in a database, or sent over between machines, like
from a server to a browser.

81
Serialization is the process of turning a
data object into a series of bytes. In the
context of JSON data, this is often called
stringifying JSON.

Deserializing is the process of turning a
series of bytes into a data object. In the
context of JSON data, this is often called
parsing JSON.

►JavaScript has a built-in functions JSON.parse and JSON.stringify to work
with JSON. 82
const jsonString =
'{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":false}'
const parsedJson = JSON.parse(jsonString)
console.log(parsedJson.name)
//output
Joe
parsedJson.winner = true
const stringifiedJson = JSON.stringify(parsedJson)
console.log(stringifiedJson)
//output : Serialize
{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":true}

►JavaScript has a built-in functions JSON.parse and JSON.stringify to work with JSON.
83
//output : stringify formatted JSON
{
"name": "Joe",
"age": 42,
"scores": [
31.4,
29.9,
35.7
],
"winner": true
}
const formattedJson = JSON.stringify(parsedJson, null, 2)
console.log(formattedJson)
JSON.stringify()
•Converts a JavaScript object/array/value into a JSON string.
•Useful when you want to send data to a server or store it (e.g., in a
file or local Storage).
JSON.parse()
•Converts a JSON string back into a JavaScript object/ array/ value.
•Useful when you receive JSON data (e.g., from an API or local
Storage).

AJAX
ASYNCHRONOUS JAVASCRIPT AND XML
A Group of Web Development Techniques used to create
Asynchronous Web Applications

84

Synchronous Vs Asynchronous
Synchronous
►Script stops and waits for the server to send
back a reply before continuing
►Like reloading the page but with only the
requested information having to be download
instead of the entire page
►Faster then not using AJAX
85
ASynchronous
►Script Allows the page to continue to be
processed and will handle the reply if and when
it arrives.
►Avoid the delay while the retrieval from the
server

What is AJAX?
►AJAX is not a programming language.
►AJAX just uses a combination of:
►A browser built-in XMLHttpRequest object (to request data from a web server)
►JavaScript and HTML DOM (to display or use the data)
►AJAX requests are not saved in browser history
86
AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.

How AJAX Works
87


Example:
A WEB page can make a request to, and get response from a web server
– Without reloading the page.

XMLHttpRequest Object in Ajax
88



An object of XMLHttpRequest is used for asynchronous communication between
client and server.
Java Script communication directly with the server, through the Java Script
XMLHTTPRequest
It performs following operations:
• Sends data from the client in the background.
• Receives the data from the server.
• Updates the webpage without reloading it.
:
Syntax for creating an XMLHttpRequest object:
var variable=new XMLHttpRequest();

XMLHttpRequest Object in Ajax
89

XMLHttpRequest Properties
90
•responseText
response data as plain text string

•responseXML
response data as XML data

•onreadystatechange
stores a function to be called
automatically every time the readyState
value changes
•readyState
integer, values range 0 – 4 according to request state
•0 : not initialized
•1 : connection established
•2 : request received
•3 : processing request
•4 : request finished and response ready

•status
HTTP status code, e.g. 200, 404, 403, etc…
200: "OK"
403: "Forbidden"
404: "Not Found

XMLHttpRequest Methods
91
•open(method, url, asynch, user, pass)
creates a connection to specified URL preparing the request to be sent
•method: HTTP method (GET / POST)
•url: url to the server-side script or resource
•asynch (optional): when true (default) request is asynchronous, when false request is
synchronous
•user (optional): username for HTTP Authentication
•pass (optional): password for HTTP Authentication
•send(params) - sends the request off to the server
params: string containing POST parameters, set to null in case of GET

•abort() - completely aborts/cancels the request

•getAllResponseHeaders - returns all headers of the response as a hash (map)

•getResponseHeader(headerName) - returns specific header such as User-Agent
headerName: name of header to retrieve

First AJAX Request
1.Create XMLHttpRequestObject
request = new XMLHttpRequest();
2.Prepare callback function
request.onreadystatechange = function() {
if (request.readyState == 4) {
// response ready, time to update DOM
} else {
// not ready, show progress animation
}
};
2.Open connection and send
// open connection to my server-side script
request.open(‘GET’, ‘http://mydomain/script.php’, true);
// send off the request
request.send(null);




92
Request to Server:
The XMLHttpRequest object sends
an HTTP request to a web server.
This request can be a GET request
to retrieve data or a POST request
to send data

93
<html>
<body>
<form method=“POST” name=“myform” action=“”>
<input type=“button” value=“Fire Request” onclick=“handleUserAction()” />
<input type=“text” name=“res” />
</form>

94
<script type=“text/javascript”>
var xhr = null
function handleUserAction() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = xhrCallback;
xhr.open(‘GET’, ‘data.txt’, true);
xhr.send(null);
}
function xhrCallback() {
if (xhr.readyState == 4) {
document.myform.res.value = xhr.responseText
} else {
document.myform.res.value = ‘err: ‘ + xhr.status;
}
}
</script> </body></html>
1.Create a html file with script
2.(Have data file or json file)
3.link a node js file and run it
Returns the response data as a string
open(method, url, async)

Send a Request to Server using Ajax
95
XMLHttpRequest Object, following
methods are allow to interact with
the server.
GET Method
var xhr=new XMLHttpRequest();
xhr.open("GET", url, true)
xmlhttp.send()

Post Method
var xhr=new XMLHttpRequest();
xhr.open("POST", url, true)
xmlhttp.send(String)

96
/*index1.html*/
<html>
<head>
<title>Simple Ajax Example</title>
</head>
<body>
<h2>Load Data with Ajax</h2>
<button onclick="loadData()">Click to Load</button>
<p id="result"></p>
<script>
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "user.json", true);
xhr.onload = function() {
if (xhr.status === 200) {
const user = JSON.parse(xhr.responseText);
document.getElementById("output").innerHTML =
`<p>Name: ${user.name}</p><p>Age: ${user.age}</p>`;
}
};
xhr.send();
}
</script></body></html>

/*user.json*/
{
"name": "Alice",
"age": 22
}

/*server.js*/
const express = require("express");
const app = express();
app.use(express.static(__dirname));
app.listen(3000);

Fetch API
►The Fetch API provides a JavaScript interface for making HTTP requests and processing the
responses.
►The fetch() function returns a Promise which is fulfilled with a Response object representing
the server's response.
97
Simple
GET
request
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`
); }
return response.json(); // Parse JSON
})
.then(data => { console.log(data); }) // fetched data
.catch(error => { console.error('Error fetching data:', error);
});

Fetch API
some key features and benefits of the Fetch API:
►Promise-based: Fetch is built on promises, providing a more readable and manageable way
to handle asynchronous operations.
►Improved Error Handling: Fetch allows you to easily catch and handle errors, ensuring more
robust applications.
►Flexible and Extensible: Fetch supports a wide range of options and configurations, making it
adaptable to various needs, from simple GET requests to complex POST operations.
98

99
/*index1.html*/
<html>
<head>
<title>Simple Ajax Example</title>
</head>
<body>
<h2>Load Data with Ajax</h2>
<button onclick="loadData()">Click to Load</button>
<p id="result"></p>
<script>
function loadData() {
fetch("user.json")
.then(response => response.json())
.then(data => {
document.getElementById("result").innerHTML =
`<p>Name: ${data.name}</p><p>Age: ${data.age}</p>`;
}); }
</script></body></html>

/*user.json*/
{
"name": "Alice",
"age": 22
}

/*server.js*/
const express = require("express");
const app = express();
app.use(express.static(__dirname));
app.listen(3000);

MongoDB
100

Organization uses Mongo DB
101

►MongoDB is an open-source document-oriented database (key-value pair)
►A NoSQL database, a non-relational database, can process structured,
semi-structured, and unstructured data.
►Data is stored in JSON-like documents with dynamic schemas.
►As of February 2015, MongoDB was the fourth most popular database
management system. It was developed by a company 10gen which is now
known as MongoDB Inc.


102

MongoDB Editions
MongoDB has three editions: community server, enterprise server, and atlas.

1) MongoDB Community Server :
The MongoDB Community Edition is free and available on Windows, Linux, and macOS.

2) MongoDB Enterprise Server :
MongoDB Enterprise Server is a commercial edition of MongoDB as a part of the MongoDB
Enterprise Advanced subscription.

3) MongoDB Atlas :
MongoDB Atlas is a global cloud database service. It is a database as a service that allows
you to focus on building apps rather than spending time managing the databases.
103

MongoDB Basics
►Database
►Database is a physical container for collections. Each database gets its own set of files on
the file system.
►A single MongoDB server typically has multiple databases

104
•NoSQL database is a highly scalable and flexible
database management system.
•NoSQL database allows users to store and process
unstructured and semi-structured data; this feature is
impossible in RDBMS tools.

105

Database
A database can be referenced by a name, for example bookdb.
The database names cannot:
►Be an empty string ("").
►Contain any of these characters: /, \, ., “, *, <, >, :, |, ?, $, (a single space), or \0 (the null
character).
►Exceed the maximum size which is 64 bytes.
MongoDB also has some reserved database names such as admin, local, and config that you
cannot use to create new databases.

106

MongoDB Structure
►MongoDB stores data in collections and documents.
►A collection is a group of MongoDB documents
►A document is a set of key-value pairs.

107
►Collection : A container for documents (like a table).
►Document : A JSON-like record within a collection (like a
row).
►Field : A key-value pair within a document (like a column).

MongoDB Basics
►Data formats
►MongoDB documents are similar to JSON objects.

108
JSON stands for JavaScript Object Notation. JSON syntax is based on a subset of JavaScript
ECMA-262 3rd edition.
A JSON document is a collection of fields and values in a structured format.

109
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Table Join Embedded Documents
Primary KeyPrimary Key (Default key _id
provided by mongodb itself)
Database Server and Client
Mysqld/Oracle mongod
mysql/sqlplus mongo

MongoDB Basics
►A document is a set of field-and-value pairs with the following structure:
{
field_name1: value1,
field_name2: value2,
field_name3: value3,
...
}
In this syntax, the field names are strings and values can be numbers, strings, objects, arrays, etc.

110
Field names have the following restrictions:
•MongoDB reserves the field_id and uses it to uniquely identify the document.
•Field names cannot contain null characters.
•Top-level field names cannot start with the dollar sign ($) character.
A document is similar to a row in a table

Namespace

►A namespace is a concatenation of the database name with a collection in
that database. Namespaces allow you to fully qualify collections.
►For example, if the collection name is books and database name is bookdb, the
namespace of the books collection would be bookdb.books.
111

Installation
►Download MongoDB - Download and use the MongoDB open source Community Server on your device for free.
https://www.mongodb.com/try/download/community-edition
Version: Latest (e.g., 8.0 or 8.2)
Platform: Windows
Package: MSI
►Install MongoDB - Select Run service as Network Service user
►Check where MongoDB got installed. (eg: C:\Program Files\MongoDB\Server\8.2\bin)
►Add MongoDB to System PATH - Press Win + R, type:sysdm.cpl
►Go to Advanced → Environment Variables. Under System variables, find Path → Edit. Click New → add this path
►Install MongoDB Shell (mongosh)
►select .msi file and install

112
•Go to Advanced → Environment Variables.
•Under System variables, find Path → Edit.
•Click New → add this path
select .msi file

Installation
-Check
113
•Go to Advanced → Environment Variables.
•Under System variables, find Path → Edit.
•Click New → add this path

►MongoDB allows users to interact with the MongoDB Server through two interfaces.
►Mongo shell command-line interface of the MongoDB server.
►MongoDB Compass GUI tool , which is used to query and analyze MongoDB data visually.
►MongoDB Compass is open-source and is available for operating systems like Linux, Windows, macOS,
etc. MongoDB Compass is a perfect alternative to the MongoDB Shell.
►Install the MongoDB Compass - Choose the Community Edition Stable version
►connect it to the MongoDB instance. Set the parameters as mentioned below:
►Hostname as Localhost and Port as 27017.
►Click on connect as the rest of the fields are default.
►In MongoDB Compass, you can Insert Documents in two types:
►Import JSON or CSV file.
►Insert data manually.

114

115
The GUI for MongoDB.

Basic MongoDB Commands
►View current database : db
►Show all databases : show dbs
►Create a new or switch databases : use dbName
►Delete current database: db.dropDatabase()
116
Inside mongosh:
1. Database Commands

Basic MongoDB Commands
►Show collections : show collections
►Create a collection named ‘comments’: db.createCollection('comments')
►Insert document data :


►Show all documents in a collection :


117
2. Collections Commands

Basic MongoDB Commands
►Search by field :
►Limit the number of results :
►Skip results (useful for pagination) :
►Count the number of matching documents :
►Update data :
118
2. Collections Commands

Basic MongoDB Commands
►Drop a collection : db.COLLECTION_NAME.drop()
►Delete document : > db.students.deleteOne({ name: "Bob" })
db.students.deleteMany({ course: "Math" })
►Rename a field :

119
2. Collections Commands

Basic MongoDB Commands
120
2. Query Operators
2.1 Comparison Operators

•db.comments.find({member_since: {$lt: 90}}) // less than
•db.comments.find({member_since: {$lte: 90}}) // less than or equal
•db.comments.find({member_since: {$gt: 90}}) // greater than
•db.comments.find({member_since: {$gte: 90}}) // greater than or equal
•db.comments.find({member_since: {$ne: 5}}) // not equal

Basic MongoDB Commands
121
2. Query Operators
2.2 Logical Operators
•db.comments.find({$and: [{lang: 'Python'}, {member_since: {$gt: 2}}]})
•db.comments.find({$or: [{lang: 'Python'}, {lang: 'Java'}]})
•db.comments.find({lang: {$in: ['Python', 'Java']}})
•db.comments.find({lang: {$nin: ['C++', 'Rust']}})
2.3 Sorting Operators
•db.comments.find().sort({member_since: 1}) // ascending
•db.comments.find().sort({member_since: -1}) // descending

MongoDB Node.js Database Interaction
122
MongoDB Node.js Driver Installation
To use MongoDB with Node.js, you will need to install the mongodb package in your
Node.js project.
npm install mongodb
Create an index.js file in your project directory.




Connection String
const url = 'mongodb://localhost:27017';

123
// MongoDB Example Program
const { MongoClient } = require('mongodb'); // Importing the MongoClient class from MongoDB Node.js driver.
const url = 'mongodb://localhost:27017'; // Connection string to connect to your local MongoDB instance
const client = new MongoClient(url); // Creates a new MongoClient object with that URL.
async function run() {
try {
await client.connect(); // Establishes the connection to MongoDB.
const db = client.db('testdb'); //Chooses (or creates if not exists) a database named ‘testdb’.
const collection = db.collection('users'); //Chooses (or creates if not exists) a collection named ‘users’ inside testdb.
const result = await collection.insertOne({ name: "John Doe", age: 30 });
console.log(`Document inserted with _id: ${result.insertedId}`);
} finally {
await client.close();
}}run();

Develop a Node.js script that connects to a MongoDB database
and retrieves all student records where the department is "CSE".124
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function main() {
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db(dbName);
const collection = db.collection('students');
const students = await collection.find({ department: 'CSE' }).toArray();
console.log('CSE Students:', students);
}
catch (err) { console.error('Error:', err); }
finally { await client.close(); }
}findCseStudents();

Homework
►Construct and execute the Commands of MongoDB: Insert, Query, Update, Delete and
Projection. (Note: use any collection).
►Illustration of AND,OR operations commands in MongoDB.
►Develop a MongoDB query to select certain fields and ignore some fields of the documents
from any collection.
►Write code to perform Insert, find, update, and delete operations on Student database using
Node.js and MongoDB.


125

126
MongoDB Mongoose
A NoSQL document-oriented database.
An ODM library for MongoDB, providing
schema-based data modeling.
Flexible, no predefined schema.
Enforces schema with data types, validation,
and structure.
Supports basic CRUD operations and direct
database manipulation.
Provides higher-level abstraction with
middleware, validation, and query building.
No built-in data consistency enforcement.
Enforces data consistency through schema
validation.
Low-level API to interact with MongoDB
directly.
High-level API for managing models and
interactions with MongoDB

127
Mongoose is a JavaScript object-oriented programming library that creates a connection
between MongoDB and the Node.js JavaScript runtime environment.
Mongoose includes built-in type casting, validation, query building, business logic hooks etc.
Mongoose to help with data modeling, schema enforcement, model validation, and general
data manipulation.
Schemas
A schema defines the structure of your collection documents.
A Mongoose schema maps directly to a MongoDB collection.

►Install mongoose in your Node.js project:



►Connect to MongoDB
import mongoose from 'mongoose';
mongoose.connect("<connection string>")
Eg:
mongoose.connect("mongodb://127.0.0.1:27017/testdb")
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.error("Connection failed", err));

128
npm init -y # if you don’t have a package.json
npm install mongoose
1. Installation and Setup

►2.1 Schema Definition
►A schema defines the structure of the documents within a MongoDB collection.
►It outlines the fields and their types, validation, default values, and more
129
2. Schema and Model in Mongoose
const mongoose = require('mongoose');
// Define a schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true, },
email: { type: String, required: true, unique: true, },
age: { type: Number, min: 18, },
createdAt: { type: Date, default: Date.now, },
});


// Create a model based on the schema
const User = mongoose.model('User', userSchema);
module.exports = User;

►2.2 Model Creation
►A model is a constructor function that allows us to create and interact with
documents that follow the schema.
const User = mongoose.model('User', userSchema);
►After defining the model, you can perform operations like creating, reading,
updating, and deleting (CRUD) documents in the associated MongoDB collection.
130
2. Schema and Model in Mongoose

Insert Documents 131
async function createUser() {
const user = new User({ name: "Alice", age: 25, email: "[email protected]" });
await user.save();
console.log("User saved:", user);
}
createUser();
Find Documents
async function findUsers() {
const users = await User.find(); // get all users
console.log(users);
}
findUsers();

Update Documents
132
async function updateUser() {
const user = await User.findOneAndUpdate(
{ name: "Alice" }, { age: 30 }, { new: true } // return updated doc
);
console.log("Updated:", user);
}
updateUser();
Delete Documents
Delete Documents async function deleteUser() {
const result = await User.deleteOne({ name: "Alice" });
console.log("Deleted:", result);
}
deleteUser();

133
// Import mongoose
const mongoose = require("mongoose");
// Connect to MongoDB
mongoose.connect("mongodb://127.0.0.1:27017/testdb",)
.then(() => console.log(" Connected to MongoDB"))
.catch(err => console.error(" Connection error:", err));
// Define a schema
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
course: String,
marks: {math: Number, english: Number, programming: Number}
});
// Create a model
const Student = mongoose.model("Student", studentSchema);
// CRUD operations
async function run() {
// INSERT
const student = new Student({
name: "Alice Johnson",


age: 20,
course: "Computer Science",
marks: { math: 85, english: 78,
programming: 92 }
});
await student.save();
console.log("Student Inserted:", student);
// READ
const students = await Student.find();
console.log("All Students:", students);
// UPDATE
const updated = await Student.updateOne(
{ name: "Alice Johnson" }, { $set: { age: 21 } } );
console.log("Update Result:", updated);
// DELETE
const deleted = await Student.deleteOne({ name: "Alice " });
console.log("Delete Result:", deleted);
mongoose.connection.close();
}
run();

Overview of PHP and Python
for backend development
134

PHP (Hypertext Preprocessor)
►Open-source language, easy to download and use.
►server-side scripting language.
►used for creating dynamic HTML content over the web.
►Embedded in HTML
►Interacting with databases for data storage and retrieval. (Databases:MySQL,
PostgreSQL, Oracle).
►Handling form data and user authentication.
►Generating various output types, including images, PDFs, JSON, and XML.
135

Python
►Python is a high level interpreted and object-oriented programming language that enormous
library support and is used for developing standalone programs and scripting algorithms for
various domains.
►It was created by Guido Van Rossum and released its first version in the year 1990.
►Python is powerful, portable, open source and is relatively easy to learn and fun to use.
►It's syntax is simpler and code is more readable in Python compared to other
programming languages like PHP, C and C++.
►Its features support automatic garbage collection.
►It supports an interactive mode of testing and debugging.
136

137
https://www.geeksforgeeks.org/blogs/backend-development/

138
Python PHP
Easy to learn. Many beginners pick Python as their
programming language.
Not developed as a general-purpose language, but fairly
easy to learn
Excellent community support Excellent community support
Exceptionally well-developed library support for almost all
types of applications
Vastly fewer libraries,, Packagist being a notable library
Database integration is not as strong as that of PHP Provides access to more than 20 different databases
Can be slow depending on the application Comparatively faster
Django, Flask, Pylons, Pyramid Codeigniter, Zend, Laravel, Symfony
PDB (Python Debugger) XDebug package for debugging

•For operating in the areas of robotics and data science.
•When you want accurate and extensive data analytics.
•Developing websites using the Django framework.

•For developing blogs, websites, and web applications.
•Work effectively on the server side.
•Less investment.
Tags