Fullstack Notes With Programs
Fullstack Notes With Programs
What is JavaScript?
JavaScript (JS) is a high-level, dynamic programming language primarily used for web
development. It enables interactivity on websites, such as animations, form validations, dynamic
content updates, and more.
Key Features:
Client-Side Execution: Runs in web browsers without requiring additional software.
Event-Driven: Reacts to user interactions (clicks, scrolls, etc.).
Asynchronous Processing: Uses callbacks, promises, and async/await for non-blocking
execution.
Object-Oriented & Functional: Supports multiple programming paradigms.
^ - beginning symbol
$ - ending symbol
/ ………. / eg :- /^gmail$/
[a-z] [A-Z] [0-9]
/yahoo/ means any number of characters followed by yahoo followed by any number of characters
/^yahoo$/ means exactly yahoo [ ^ means beginning , $ means at the ending ]
program
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
var y=/^([a-z]|[A-Z]){1,25}[0-9]*\@([a-z]|[A-Z]){2,10}\.([a-z]|[A-Z]|.){3,5}$/;
if(x.match(y))
alert(" Valid email ");
else
alert("In valid email ");
}
</script>
</head>
<body>
<h3>EMAIL VALIDATION </h3>
ENTER EMAIL :
<input type="text" id="myText">
<button onClick="myFunction()">Try it</button>
<p id="demo"> </p>
</body>
</html>
********************************************************************************
*****
SIMPLE CALCULATOR
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<input type="text" id="display" disabled>
<br>
<div class="buttons">
<button onclick="appendNumber(1)">1</button>
<button onclick="appendNumber(2)">2</button>
<button onclick="appendNumber(3)">3</button>
<button onclick="appendNumber(4)">4</button>
<button onclick="appendNumber(5)">5</button>
<button onclick="appendNumber(6)">6</button>
<button onclick="appendNumber(7)">7</button>
<button onclick="appendNumber(8)">8</button>
<button onclick="appendNumber(9)">9</button>
<button onclick="appendNumber(0)">0</button>
<button onclick="clearDisplay()">C</button>
</div>
<br>
<button onclick="setOperator('+')">+</button>
<button onclick="setOperator('-')">-</button>
<button onclick="setOperator('*')">*</button>
<button onclick="setOperator('/')">/</button>
<br>
<button onclick="calculate()">=</button>
<h3>Result: <span id="result">0</span></h3>
</div>
<script>
let currentInput = "";
let operator = "";
let firstNumber = "";
function appendNumber(num) {
currentInput += num;
document.getElementById("display").value = currentInput;
}
function setOperator(op) {
if (currentInput === "") return;
firstNumber = currentInput;
operator = op;
currentInput = "";
document.getElementById("display").value = "";
}
function calculate() {
if (firstNumber === "" || currentInput === "") return;
let num1 = parseFloat(firstNumber);
let num2 = parseFloat(currentInput);
let result = 0;
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num2 !== 0 ? num1 / num2 : 'Cannot divide by zero'; break;
default: result = 'Error';
}
document.getElementById("result").innerText = result;
document.getElementById("display").value = result;
currentInput = "";
firstNumber = "";
operator = "";
}
function clearDisplay() {
currentInput = "";
firstNumber = "";
operator = "";
document.getElementById("display").value = "";
document.getElementById("result").innerText = "0";
}
</script>
</body>
</html>
********************************************************************************
******
PROGRAMS ON CREATING DYNAMIC HTML
<html>
<head>
<title> Dynamic Colors
</title>
<script>
function setColor(where, newColor) {
if (where == "background" )
document.body.style.backgroundColor = newColor;
else
document.body.style.color = newColor;
}
</script>
</head>
<body>
<p style = " font-family: Times; font-style: italics;
font-size: 24pt;">
Demonstration on dynamic settings of the
foreground and background colors.
</p>
<form>
<p>
Background color:
<input type= "text" name="background" size ="10"
onchange = "setColor('background', this.value)" />
<br />
Foreground color:
<input type= "text" name="foreground" size ="10"
onchange = "setColor('foreground', this.value)" />
<br />
</p>
</form>
</body>
</html>
<html>
<head>
<title>
Dynamic fonts for links
</title>
<style type ="text/css">
.regText { font: Times; font-size:16pt;}
</style>
</head>
<body>
<p class ="regText">
Mouseover on below paragraph
<p style = "color: blue;"
onmouseover = "this.style.color = 'red';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'blue';
this.style.font = 'normal 16pt Times';" >
This is working great ! </p>
Simple demonstration on font change.
</p>
</body>
</html>
3. Moving image based on x and y given coordinates
<html>
<head>
<title>
Moving elements
</title>
<script type = "text/javascript">
<!--
// The event handler function to move and element
<body>
<form action ="">
<p>
x coordinate:<input type= "text" id ="leftCoord" size ="5" />
<br />
y coordinate: <input type= "text" id ="topCoord" size ="5" />
<br />
<input type= "button" value = "Move it" onclick =
"moveIt('div1',document.getElementById('topCoord').value,
document.getElementById('leftCoord').value)" />
</P>
</form>
<div id ="div1" style = "position: absolute; top: 115 px; left: 0;">
<img src= "computer.jpg" />
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function demo(x)
{
x.remove();
}
</script>
<style>
.myDiv1 {
border: 10px outset black;
background-color: grey;
text-align: center;
}
.myDiv2 {
border: 10px outset green;
background-color: lightgreen;
text-align: center;
}
.myDiv3 {
border: 10px outset red;
background-color: lightpink;
text-align: center;
}
</style>
</head>
<body>
<h1>Div element - Click on boxes to vanish - Using java script</h1>
<p id="p1"></p>
<div id="div1" class="myDiv1" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>
<br>
<div id="div2" class="myDiv2" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>
<br>
<div id="div3" class="myDiv3" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>
</body>
</html>
********************************************************************************
**********************
Reactjs :
React.js is a JavaScript library developed by Meta (Facebook) for building user interfaces
(UIs), especially for single-page applications (SPAs). It allows developers to create reusable UI
components and manage application states efficiently.
function App() {
return (
<div>
<h1>Hello, React!</h1>
<p>Welcome to my first React.js app.</p>
</div>
);
}
How It Works
The App function is a React component that returns JSX (HTML-like syntax in
JavaScript).
<h1> and <p> are displayed in the browser.
export default App; allows this component to be used in main.jsx.
Open http://localhost:5173/ in your browser, and you will see:
Hello, React!
Welcome to my first React.js app.
********************************************************************************
***************
Angularjs :
What is AngularJS?
AngularJS is a JavaScript framework developed by Google in 2010 for building dynamic web
applications. It extends HTML with additional attributes (called directives) and follows the
Model-View-Controller (MVC) architecture.
📌 Important Note:
AngularJS (1.x) is the old version, which is now obsolete.
Angular (2+) is the modern version (completely different from AngularJS).
Most new projects use Angular (2+), not AngularJS.
Basics of AngularJS -- Key Features:
1. Two-Way Data Binding – Auto-updates UI when data changes.
2. Directives (ng-*) – Custom HTML attributes (ng-model, ng-repeat).
3. Dependency Injection (DI) – Manages dependencies automatically.
4. MVC Architecture – Divides code into Model, View, Controller.
5. Single Page Application (SPA) Support – Loads content dynamically.
Differences between React and Angular
********************************************************************************
**************
Express framework:
Express.js is a fast, minimal, and flexible web framework for Node.js that simplifies building
web applications and APIs.
It provides:
✅ Routing – Handles different URLs (/home, /about).
✅ Middleware – Processes requests before sending responses.
✅ Request & Response Handling – Easily handle GET, POST, PUT, DELETE requests.
✅ Template Engines – Supports rendering HTML dynamically (EJS, Pug, Handlebars).
✅ REST API Support – Ideal for creating APIs.
********************************************************************************
******************
MongoDB basics
As part of unit-1 , you will study introduction and only basic commands
MongoDB Overview
MongoDB is a NoSQL database that stores data in a document-oriented format using BSON
(Binary JSON). Unlike relational databases, which store data in tables with fixed schemas,
MongoDB uses flexible, schema-less collections.
Key Features
Document-Oriented: Stores data as JSON-like documents.
Schema Flexibility: No fixed schema; each document can have different fields.
Scalability: Supports horizontal scaling through sharding.
Indexing: Supports various types of indexes for efficient querying.
Aggregation Framework: Performs complex data manipulations.
What is a Collection in MongoDB?
A collection in MongoDB is equivalent to a table in a relational database. It is a group of
documents (records) that share a common purpose but do not necessarily have a fixed schema.
Key Features of a Collection:
1. Schema-less: Documents within a collection can have different fields and structures.
2. Stores Documents: Each document is stored in BSON (Binary JSON) format.
3. Dynamic Growth: Collections are automatically created when you insert a document.
4. Indexing Support: You can create indexes to speed up queries.
Basic commands :
1. Connect to database
mongod
5. creating collections
db.createCollection("students")
6. Insert a document
db.students.insertOne({name: "Alice", age: 22, course: "CS"})
********************************************************************************
*****************
Introduction to Nodejs
node -v
npm -v
If installed correctly, this will display the versions of Node.js and npm.
Install Node.js
bash
sudo apt install nodejs -y
Verify installation
bash
node -v
npm -v
powershell
nvm install 20
(Replace 20 with the required version)
powershell
nvm use 20
Verify installation
powershell
node -v
npm -v
********************************************************************************
*******************
Creating Your First "Hello World" Application in Node.js
// Create a server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
// Define a port
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
open terminal and type node app.js ( where app.js is above file name)
when you run, web server will be running in port 3000
Type localhost:3000 in your browser then you can see the output as HelloWorld
Note that res is inbuilt response object. It is used to send response to the user. In the same way, we
do have req inbuilt request object. Ofcos, this object is not used in the above program. It is used to
take input from user.
********************************************************************************
*********************
Understanding Nodejs architecture, Event Modules and How to add work to event Queue
Users send requests (blocking or non-blocking) to the server for performing operations.
The requests enter the Event Queue first at the server-side.
The Event queue passes the requests sequentially to the event loop. The event loop checks
the nature of the request (blocking or non-blocking).
Event Loop processes the non-blocking requests which do not require external resources and
returns the responses to the corresponding clients
For blocking requests, a single thread is assigned to the process for completing the task by
using external resources.
After the completion of the operation, the request is redirected to the Event Loop which
delivers the response back to the client.
🔹 (4) I/O Queue (Using Asynchronous File Reads, Network Requests, etc.)
What it does? Adds I/O tasks (e.g., file system operations, database queries) to the event
queue.
How it works? Once the I/O operation completes, the event loop picks up the corresponding
callback function and executes it.
Theory:
Asynchronous I/O operations in Node.js do not block the execution. Instead, they are handled by
background workers. Once an operation is finished, its callback is queued and executed when the
event loop reaches the I/O phase.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging
data between a server and a client. It is easy to read, write, and parse, making it widely used in
web APIs, databases, and configurations.
Buffer Concatenation
If you receive data in chunks, you can concatenate buffers:
const buf1 = Buffer.from("Hello ");
const buf2 = Buffer.from("World");
const combined = Buffer.concat([buf1, buf2]);
The Stream module in Node.js is a built-in module that allows handling data in chunks instead of
loading everything into memory at once. This is useful for working with large files, network
requests, and real-time data processing.
Types of Streams
Node.js provides four types of streams:
You will learn how streams are used in next section along with file modules.
********************************************************************************
*****************
Accessing files using file module in Nodejs :- open, read, write and close
In Node.js, you can interact with the file system using the built-in fs (File System) module. This
module allows you to perform operations such as reading, writing, opening, closing, and deleting
files.
Reading a File with Explicit Open and Close
Here, we manually open the file using fs.open(), read it using fs.read(), and then close it using
fs.close().
const fs = require('fs');
const filePath = 'example.txt';
// Open the file for reading
fs.open(filePath, 'r', (err, fd) => {
if (err) {
console.error('Error opening file:', err);
return;
}
SERVER.JS file
const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");
server.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
Nodejs Program to read form data from query string and generate response
Explanation about program
There are two files. One is form.html and other is server.js. First run the server file in node
environment. Open browser and type localhost:3000 then form.html will be loaded on webpage.
Provide input and press submit. You will see form data is accessed via query string and displayed on
the web page.
1. Form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form</title>
</head>
<body>
<h2>User Registration Form</h2>
<form action="/submit" method="GET">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label>Skills:</label><br>
<input type="checkbox" name="skills" value="C"> C<br>
<input type="checkbox" name="skills" value="C++"> C++<br>
<input type="checkbox" name="skills" value="Java"> Java<br>
<input type="checkbox" name="skills" value="Python"> Python<br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male"> Male<br>
<input type="radio" name="gender" value="Female"> Female<br><br>
<label for="location">Location:</label>
<select id="location" name="location">
<option value="Hyderabad">Hyderabad</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select><br><br>
2. Server.js
const responseHTML = `
<html>
<head><title>Form Submission</title></head>
<body>
<h2>Submitted Data</h2>
<p><strong>Username:</strong> ${username}</p>
<p><strong>Password:</strong> ${password}</p>
<p><strong>Skills:</strong> ${skills}</p>
<p><strong>Gender:</strong> ${gender}</p>
<p><strong>Location:</strong> ${location}</p>
<a href="/">Go Back</a>
</body>
</html>
`;
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<p id="message"></p>
</body>
</html>
2. Server.js
const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');
req.on('end', () => {
const postData = querystring.parse(body);
const { username, password } = postData;
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
********************************************************************************
*****************
OS Module in Nodejs
The os module in Node.js is a built-in module that provides operating system-related utility
methods and properties. It allows you to interact with the underlying operating system, retrieve
system-related information, and perform various OS-level operations. This module is useful for
system monitoring, logging, and performance optimization in Node.js applications
How to Use the os Module
To use the os module, you need to require it in your Node.js script:
const os = require('os');
Commonly Used Methods
1. Get OS Platform
console.log(os.platform()); // Outputs: 'win32', 'linux', 'darwin' (macOS)
2. Get OS Architecture
console.log(os.arch()); // Outputs: 'x64', 'arm', 'ia32', etc.
3. Get CPU Information
console.log(os.cpus()); // Returns an array of CPU core details
4. Get Free Memory
console.log(os.freemem()); // Returns available system memory in bytes
5. Get Total Memory
console.log(os.totalmem()); // Returns total system memory in bytes
6. Get Hostname
console.log(os.hostname()); // Returns the system's hostname
7. Get Network Interfaces
console.log(os.networkInterfaces()); // Returns an object with network details
8. Get OS Uptime
console.log(os.uptime()); // Returns system uptime in seconds
9. Get User Info
console.log(os.userInfo()); // Returns information about the current user
10. Get Home Directory
console.log(os.homedir()); // Returns the home directory path
********************************************************************************
********************
UTIL Module in nodejs :-
The util module in Node.js provides utility functions that help with debugging, formatting, and
working with objects, callbacks, and inheritance. It is part of Node.js's standard library and does not
require installation.
How to Use the util Module
First, you need to import the module:
javascript
CopyEdit
const util = require('util');
Key Functions in util:
1. util.format()
Formats strings like printf in C.
console.log(util.format('%s is %d years old.', 'Alice', 25));
// Output: Alice is 25 years old.
2. util.promisify()
Converts a callback-based function into a Promise-based function.Example:
const fs = require('fs');
const readFile = util.promisify(fs.readFile);
readFile('example.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
3. util.inherits()
Helps with prototype-based inheritance.
Example:
const EventEmitter = require('events');
function MyClass() {
EventEmitter.call(this);
}
util.inherits(MyClass, EventEmitter);
The dns module in Node.js provides functions to perform Domain Name System (DNS) lookups
and resolve domain names into IP addresses. It allows applications to interact with DNS servers,
retrieve records, and perform hostname resolution.
How to Use the dns Module in Node.js
The dns module comes built-in with Node.js, so you don’t need to install it separately. You can use
it by requiring the module.
1. Import the dns module
const dns = require('dns');
B) dns.resolve()
Retrieves DNS records for a given hostname.
C) dns.reverse()
Finds the hostname for a given IP address.
D) dns.resolveMx()
Retrieves Mail Exchange (MX) records for email routing.
resolveDNS();
4. Configure Custom DNS Server
By default, Node.js uses the system’s DNS settings. You can change the DNS server using:
********************************************************************************
*************
CRYPTO Module in Nodejs
The crypto module in Node.js provides cryptographic functionality, including hashing, encryption,
and decryption. It allows you to perform operations like password hashing, data encryption, and
secure random number generation.
1. Importing the crypto Module
The crypto module is built into Node.js, so you don’t need to install it separately. Import it using:
const crypto = require('crypto');
console.log(`HMAC: ${hmac}`);
Uses a secret key for additional security.
// Encrypt
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// Decrypt
function decrypt(encryptedText) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
console.log(`Encrypted: ${encrypted}`);
console.log(`Decrypted: ${decrypted}`);
Uses a secret key and IV to encrypt and decrypt messages.
AES-256-CBC is a secure and widely used encryption method.
crypto.generateKeyPair('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
}, (err, publicKey, privateKey) => {
if (err) throw err;
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
});
RSA is widely used for secure communications.
generateRandomBytes();
Conclusion
The crypto module is essential for security-related tasks in Node.js, including:
Hashing (SHA, MD5)
HMAC authentication
Encryption/Decryption (AES, RSA)
Generating secure random values
********************************************************************************
****************
UNIT -3
Feature Description
{
_id: ObjectId,
name: "Alice",
email: "[email protected]",
address: { street, city, zip }
}
Collection: orders
(Embed order items inside the order for quick retrieval)
{
_id: ObjectId,
userId: ObjectId,
orderDate: ISODate,
items: [
{ productId: ObjectId, quantity: 2, price: 50 },
{ productId: ObjectId, quantity: 1, price: 100 }
],
status: "shipped"
}
********************************************************************************
******
// same process in linux – except you have to download appropriate installation file from
official website
********************************************************************************
*****
2. Documents
Like rows in SQL, but stored in BSON (Binary JSON) format.
Flexible schema: each document can have different fields.
Example:
{
_id: ObjectId("..."),
name: "Alice",
age: 25
}
3. Indexes
Improve query performance.
Similar to indexes in SQL databases.
Example:
db.users.createIndex({ email: 1 })
4. Validators
Define rules for documents in a collection.
Help maintain data quality.
Example: Ensuring a price field must be a number > 0.
5. Views (optional)
Read-only, queryable collections based on aggregation pipelines.
Like virtual tables in SQL.
**************************************************************************
After fresh installation, you will be connected to default database test. With default user with
no name that is anonymous user. No pwd is required. You can create objects like collections ,
documents etc
You can:
Create databases
Create collections
Insert documents
Read documents
Delete and update documents
Drop collections/databases
MongoDB gives full access by default in no-auth mode. This is very common in
local/development environments.
your data will persist even after you:
Close the terminal or shell (mongosh)
Restart your computer
Reconnect to MongoDB later
How to start and stop Mongodb service in Windows though command prompt
Run cmd as administrator and run this command to start
net start MongoDB
To stop the service
net stop MongoDB
Two ways to access database, one is through mongodb compass which is GUI but its
developers GUI, you cannot perform adminstrative tasks like user creation etc. Another is
mongosh which is CUI. You will get compass by mondodb installation you can also launch
mongosh from compass to perform administrative tasks
*************************************************************************
Collections vs documents in mongodb
Feature Collection Document
No fixed schema —
Schema-less, fields
Schema can contain varied
can differ per doc
docs
You query a
You read/write/update
Operations collection to get
individual docs
documents
Key Relationship
A collection is like a folder.
A document is like a file inside that folder.
***************************************************************************
Create collections in db
MongoDB is schema-less, so you don’t define fields in advance like in SQL.
Instead, you create fields while inserting documents.
4. In the same way inser another record with name rahul and display all records as follows
test> db.student.find().pretty()
[
{
_id: ObjectId('684094168927d1bb8750eb67'),
student_id: 101,
name: 'Alice',
age: 21,
course: 'CSE',
address: { city: 'Hyderabad', pincode: '500001' },
marks: [ 85, 92, 78 ]
},
{
_id: ObjectId('684094df8927d1bb8750eb68'),
student_id: 102,
name: 'Rahul',
age: 22,
course: 'ECE',
address: { city: 'Bangalore', pincode: '560001' },
marks: [ 88, 79, 91 ]
}
]
5. Applying projection – Project only student student names
Query - db.student.find({}, { name: 1, _id: 0 })
Output - [ { name: 'Alice' }, { name: 'Rahul' } ]
Explanation:
{} → No filter (i.e., select all documents)
{ name: 1 } → Project only the name field (1 means show)
{ _id: 0 } → Hide the _id field (which appears by default)
Address
id name gender salary Dept
city country
1 Aarav Mehta Male Hyderabad India 78 CSE
2 Diya Sharma Female Mumbai India 65 CSE
3 Kunal Deshmukh Male Hyderabad India 55 CSE
4 Meera Joshi Female Mumbai India 80 CSE
5 Rahul Verma Male Hyderabad India 42 CSE
6 Sneha Kapoor Female Mumbai India 72 ECE
7 Ankit Reddy Male Hyderabad India 35 ECE
8 Pooja Nair Female Mumbai India 60 ECE
9 Rohan Malhotra Male Hyderabad India 47 ECE
10 Shivani Iyer Female Mumbai India 85 ECE
11 Vikram Kumar Male Hyderabad India 53 IT
12 Nikita Shah Female Mumbai India 66 IT
13 Arjun Rao Male Hyderabad India 73 IT
14 Trisha Kulkarni Female Mumbai India 28 IT
15 Neeraj Patil Male Hyderabad India 39 IT
16 Gauri Bhatt Female Mumbai India 76 AIML
17 Rakesh Jain Male Hyderabad India 62 AIML
18 Sanjana Rao Female Mumbai India 50 AIML
19 Dhruv Singh Male Hyderabad India 83 AIML
20 Aisha Khan Female Mumbai India 44 AIML
Lets convert the above table to Json file. The following is the Json file. Name of the collection is
employee and there will be 20 documents in it.
[
{
"id": 1,
"name": "Aarav Mehta",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 78,
"department": "CSE"
},
{
"id": 2,
"name": "Diya Sharma",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 65,
"department": "CSE"
},
{
"id": 3,
"name": "Kunal Deshmukh",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 55,
"department": "CSE"
},
{
"id": 4,
"name": "Meera Joshi",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 80,
"department": "CSE"
},
{
"id": 5,
"name": "Rahul Verma",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 42,
"department": "CSE"
},
{
"id": 6,
"name": "Sneha Kapoor",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 72,
"department": "ECE"
},
{
"id": 7,
"name": "Ankit Reddy",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 35,
"department": "ECE"
},
{
"id": 8,
"name": "Pooja Nair",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 60,
"department": "ECE"
},
{
"id": 9,
"name": "Rohan Malhotra",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 47,
"department": "ECE"
},
{
"id": 10,
"name": "Shivani Iyer",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 85,
"department": "ECE"
},
{
"id": 11,
"name": "Vikram Kumar",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 53,
"department": "IT"
},
{
"id": 12,
"name": "Nikita Shah",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 66,
"department": "IT"
},
{
"id": 13,
"name": "Arjun Rao",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 73,
"department": "IT"
},
{
"id": 14,
"name": "Trisha Kulkarni",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 28,
"department": "IT"
},
{
"id": 15,
"name": "Neeraj Patil",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 39,
"department": "IT"
},
{
"id": 16,
"name": "Gauri Bhatt",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 76,
"department": "AIML"
},
{
"id": 17,
"name": "Rakesh Jain",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 62,
"department": "AIML"
},
{
"id": 18,
"name": "Sanjana Rao",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 50,
"department": "AIML"
},
{
"id": 19,
"name": "Dhruv Singh",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 83,
"department": "AIML"
},
{
"id": 20,
"name": "Aisha Khan",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 44,
"department": "AIML"
}
]
Steps to insert above documents in mongodb
1. Copy all entries
2. Create collection as follows db.createCollection("employee")
3. Use db.employee.insertMany( here paste all entries ) and execute
Alright , we are now ready with input file for learning JSON query language.
*******************************************************************************
Necessary commands
1. To show all collections you have created
Show collections
2. To show all documents in collection employee
Db.employee.find()
3. To show only necessary fields you want like name and dept only
db.employee.find({}, { name: 1, department: 1, _id: 0 })
*******************************************************************************
Applying conditions and logical operators and , or in JSON
1. Find employee details who are working for cse dept
db.employee.find({ department: "CSE" })
2. Find employee details who either work for cse or work for ece depts
Note In MongoDB, using a comma , between fields in the query works like a logical AND — it's
shorthand for combining multiple conditions.
Greater than or
$gte { marks: { $gte: 40 } }
equal to
$lt Less than { salary: { $lt: 30000 } }
Less than or
$lte { age: { $lte: 60 } }
equal to
Not in a list of
$nin { city: { $nin: ["Delhi", "Pune"] } }
values
********************************************************************************
**
Update and Delete operations
1. Update Vikram kumars salary to 60k who is an employee from IT dept.
db.employees.updateOne(
{ name: "Vikram Kumar", dept: "it" },
{ $set: { sal: 60000 } }
)
Note :- if you dont specify it dept condition then all vikarm kumars from all dept will be changed.
2. Delete employee details whose name is Dhruv Singh and works for AIML dept.
db.employees.deleteOne(
{ name: "Dhruv Singh", dept: "AIML" }
)
Notes:
deleteOne removes the first matching document. If multiple such records exist and you
want to delete all of them, use deleteMany() instead:
***************************************************************************
Find operation – similar to select in SQL
***********************************************************************
1. find employees who either work for CSE or AIML and have salary > 40
db.employee.find({
$or: [
{ department: "CSE" },
{ department: "AIML" }
],
salary: { $gt: 40 }
})
As an alternative to or in this query , you could also write the query as follows
db.employee.find({
department: { $in: ["CSE", "AIML"] },
salary: { $gt: 40 }
})
Note – in operator is easy but you cannot use where ever you use or operator. in many cases where
you're using $or for the same field, you can replace it with the simpler and more readable $in
operator.
2. find only employee names who either work for CSE or AIML and have salary > 40
db.employee.find(
{
$or: [
{ department: "CSE" },
{ department: "AIML" }
],
salary: { $gt: 40 }
},
{
name: 1,
_id: 0
}
)
**************************************************************************
Aggregation functions and Group by operations in Mongodb
The 5 main aggregate functions in MongoDB (min, max, sum, avg, count) using the aggregation
pipeline ($group):
1. Find the minimum salary across all employees.
db.employee.aggregate([
{
$group: {
_id: null,
minSalary: { $min: "$salary" }
}
}
])
2. Count total number of employees in the organization
db.employee.aggregate([
{
$group: {
_id: 0,
count: { $sum: 1 }
}
}
])
Note that even if you use id or not, it will be displayed as part of result. In compass, though
you make id as 0, it may still visible along with output
db.employee.aggregate([
{ $match: { department: "CSE" } },
{
$group: {
_id: null,
maxSalary: { $max: "$salary" }
}
}
])
Explanation:
$match filters documents where department is "CSE".
$group groups all those documents (using _id: null to group all together) and calculates the
max salary with $max.
5. Count total number of employees who are from cse and having sal >40
db.employee.aggregate([
{
$match: {
department: "CSE",
salary: { $gt: 40 }
}
},
{
$group: {
_id: null,
totalEmployees: { $sum: 1 }
}
}
])
**********************************************************************
Other commands – limit, sort, skip operations in mongodb
Limit :-
In MongoDB, limit is a method used to restrict the number of documents returned by a query.
Syntax:
db.collection.find(query).limit(n)
n is the maximum number of documents to return and query is your filter condition. Beyond limit n,
other documents will be not be returned and not printed.
Sort :-
it's used to order query results based on one or more fields.
db.collection.find(query).sort({ field: order })
eg :- db.students.find().sort({ marks: 1 }) // this is asc
eg :- db.students.find().sort({ marks: -1 }) // this is desc
Skip operation -
The skip(n) method in MongoDB is used to skip the first n documents from the query result set and
return the remaining documents.
Syntax:
db.collection.find(query).skip(n)
n: The number of documents to skip from the beginning of the query results.
Returns documents starting from the (n + 1)th document onward.
Example:
db.students.find().skip(5)
Skips the first 5 documents in the result.
Returns documents starting from the 6th document to the end.
db.collection.find().skip(5).limit(5) -- guess what this does ?
skip(5): skips the first 5 documents → so the result set starts from the 6th document onward.
limit(5): then takes only the first 5 documents from that result.
6, 7, 8, 9, 10
***********************************************************************
Creating and managing user accounts in mongodb
In MongoDB, roles define what a user can do. A role is a set of privileges (actions allowed on
resources like collections or databases). MongoDB has both:
1. Built-in roles (commonly used, predefined by MongoDB)
2. Custom roles (user-defined, if more control is needed)
Database-Specific Roles
These roles apply only within a specific database:
Role Description
read Can read all non-system collections. Cannot write.
readWrite Can read and write data (insert, update, delete).
Can perform administrative tasks like indexing,
dbAdmin
schema viewing. No read/write access by default.
Can create and manage users/roles in that
userAdmin
database.
Full control over the database (includes all of the
dbOwner
above).
readWriteAnyDatabase (admin only) Read/write access on all databases.
Create a dba user with user name and pwd with dba roles such that he/she can control only
test database
db.createUser({
user: "sateesh",
pwd: "sateesh123",
roles: [
{ role: "dbAdmin", db: "test" },
{ role: "readWrite", db: "test" }
]
})
*********************************************************************
Connecting node with Node ( with out express )
Steps :-
1. Make sure you already installed node and mongodb.
2. Download and install mongodb driver.
Command ==> npm install mongodb
***********************************************************************
1. Consider the following nodejs program to insert one record in student collection
Steps :-
1. create collection named student in your mongodb
2. run your insertstudent.js file in node. The command is as follows
npm install mongodb
Make sure, your driver package is installed
try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB");
output
Record inserted with _id: with some id value here
*********************************************************************
2. Nodejs program to take two input parameters say Student id and student name from user
through html form and prints if data is inserted successfully on web page.
Steps
1. Write index.html file
2. write insertstudent.js file
3. run the js file and also Make sure you have already student collection in mongodb. To check
whether insert happened successfully, go to mongodb and retrieve student collection.
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
2. insertrecordthroughhtmlform.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const { MongoClient } = require('mongodb');
const querystring = require('querystring');
if (!studentId || !name) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Student ID and Name are required');
return;
}
try {
const insertedId = await insertStudent({ studentId, name });
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Student details inserted successfully with id: ${insertedId}`);
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error inserting student details');
}
});
} else {
// Handle 404
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
Output:-
you can see – insert successfully on webpage. Also go to mongodb and check your student
collection.
**********************************************************************
3. Write Nodejs program which takes student id as input parameter through html form and
prints concern student name on web page.
Steps :-
1. create index.html
2. write js file
3. run the js file
<button type="submit">Submit</button>
</form>
</body>
</html>
(ii). js file.
const http = require('http');
const fs = require('fs');
const path = require('path');
const { MongoClient } = require('mongodb');
const querystring = require('querystring');
if (!studentId) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Student ID is required');
return;
}
try {
const name = await findStudentNameById(studentId);
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (name) {
res.end(`Student Name for ID ${studentId} is: ${name}`);
} else {
res.end(`No student found with ID: ${studentId}`);
}
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error querying student details');
}
});
} else {
// 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
<button (click)="logout()">Logout</button>
4. Attribute/Style/Class Binding
<div [class.active]="isActive"></div>
<div [style.color]="isWarning ? 'red' : 'black'"></div>
Features of Angular Expressions
Feature Description
No this keyword You refer to component properties directly (name, not this.name)
No control flow Cannot use if, for, while, etc.
Type-safe Only access component members (properties/methods)
Safe navigation Use ?. to avoid errors with null/undefined: user?.name
Not Allowed in Angular Expressions
Assignments: a = 10
Declarations: let, var, const
Loops or conditionals: if, for
Accessing global variables like window, document, console (for security reasons)
AngularJS Expressions (for comparison)
In AngularJS (1.x), expressions looked similar:
<p>{{ 1 + 2 }}</p>
<p>{{ user.name }}</p>
But they were evaluated differently (in the scope context, not component class), and you could use
filters like:
{{ price | currency:"USD$" }}
Summary
Use Case Expression Format Example
Interpolation {{ expression }} {{ username }}
Property Binding [property]="expression" [src]="imageUrl"
Event Binding (event)="expression" (click)="save()"
Style/Class [class.xyz]="isTrue" [style.color]="color"
************************************************************************
Data Binding in Angular
Data binding in Angular is a powerful feature that connects the component (TypeScript logic) with
the view (HTML template). It allows data to flow between the UI and the component automatically.
Purpose of Data Binding
Display dynamic data in the view.
Respond to user interactions.
Synchronize data between component and template.
Types of Data Binding in Angular
Angular provides 4 main types of data binding:
1. Interpolation – One-Way (Component ➡️ View)
Displays data from the component in the template.
Syntax: {{ expression }}
Example:
tml
CopyEdit
<p>Hello, {{ username }}</p>
2. Property Binding – One-Way (Component ➡️ View)
Binds DOM properties to component values.
Syntax: [property]="expression"
Example:
<img [src]="user.profilePictureUrl">
<button [disabled]="isLoading">Submit</button>
3. Event Binding – One-Way (View ➡️ Component)
Sends user actions (clicks, typing, etc.) to the component.
Syntax: (event)="handlerFunction()"
Example:
<button (click)="logout()">Logout</button>
4. Two-Way Binding – (Component ⬌ View)
Syncs data both ways using [(ngModel)].
Requires importing FormsModule.
Syntax: [(ngModel)]="property"
Example:
<input [(ngModel)]="user.name">
*************************************************************************
Built in Directive vs Custom Directives
Types of Directives in Angular
Angular provides two categories:
1. Built-in Directives
These are provided by Angular itself.
2. Custom Directives
These are user-defined and extend or customize behavior.
1. Built-in Directives
There are three types of built-in directives:
A. Structural Directives
Change the structure/layout of the DOM (add/remove elements).
Directive Purpose
Conditionally include or remove an
*ngIf
element
*ngFor Repeat a block for each item in a list
*ngSwitch, *ngSwitchCase, *ngSwitchDefault Conditional multi-branch rendering
Example:
<div *ngIf="isLoggedIn">Welcome!</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
B. Attribute Directives
Change the appearance or behavior of an element.
Directive Purpose
ngClass Dynamically set CSS classes
ngStyle Dynamically set styles
ngModel Two-way data binding to form inputs (in FormsModule)
Example:
html
CopyEdit
<p [ngClass]="{active: isActive}">Status</p>
<p [ngStyle]="{'color': isError ? 'red' : 'green'}">Message</p>
<input [(ngModel)]="user.name">
C. Component Directives
Technically, every component is a directive with a template.
2. Custom Directives
You can build your own directives for reusable logic or custom DOM behavior.
Example: Custom Attribute Directive
Step 1: Create Directive
bash
CopyEdit
ng generate directive highlight
Step 2: Code – highlight.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]' // use like an attribute
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Step 3: Use in Template
<p appHighlight>Hover over this text to highlight it!</p>
Summary Table
Type Examples Purpose
Structural *ngIf, *ngFor, *ngSwitch Add/remove DOM elements
Attribute ngClass, ngStyle, ngModel Change look/behavior
Custom appHighlight, appAutoFocus Your own DOM behavior
*************************************************************************
MEAN STACK – ENVIRONMENT CREATION
The below 10 steps are common for both MERN and MEAN stack. Later steps differentiate
with react and angular
1. Create fullstack directory and go to that directory
2. Go to that directory and install node and npm
3. Create backend directory (all your server app files will be here) and run this command
npm init -y
4. In the same directory install express using this command npm install express
5. In the same directory install mongodb from official website and mongodb driver using npm
command.
6. Create server.js file in same directory and copy the below content to it. This is your actually http
server. You may have to add paths in it when ever you wanted to add server side applications and
access them through http request that is you need to define route.
const express = require('express');
const app = express();
const PORT = 3000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
7. Check whether you installed node correctly or not. Type the following command
node -v
8. check whether your nodes server is running correctly by starting it.
node server.js
9. check whether your mongodb is installed correctly. Start its service by using following command
in linux --> sudo systemctl start mongod
in windows -- >net start MongoDB or goto services and start manually
To connect to mongodb, run command mongosh ( mongosh )
10. check whether express is installed correctly
npm list express
If above 10 steps are correct then it means you have node, express and mongodb perfectly in your
machine.
Installing ANGULAR– Above 10 steps are common. Below are additional steps for react.
1. Create Frontend-angular-client folder, go to that folder and Install react.
npm install -g @angular/cli (cli-command line interface)
2. To check if installation happened successfully – run this command
ng version
3. To create angular app folder, run this command
ng new my-angular-app
3. To start angulars – Development server , run this command
ng serve
go to localhost:4200 to check your angular development server is up and running.
**********************************************************************
Important -- Creating routing in Angular
1. Generate an application
The following command uses the Angular CLI to generate a basic Angular application with
application routes. The application name in the following example is routing-app.
ng new routing-app
2. Adding components for routing
To use the Angular router, an application needs to have at least two components so that it can
navigate from one to the other. To create a component using the CLI, enter the following at the
command line where first is the name of your component:
ng generate component first
Repeat this step for a second component but give it a different name. Here, the new name is second.
ng generate component second
The CLI automatically appends Component, so if you were to write first-component, your
component would be FirstComponentComponent.
3. Importing your new components in routes.ts file in app folder
To use your new components, import them into app.routes.ts at the top of the file, as follows:
import {FirstComponent} from './first/first.component';
import {SecondComponent} from './second/second.component';
Also update routes in same file
content_copyconst routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];
4. Add your routes to your application in appcomponent.html
Now that you have defined your routes, add them to your application. First, add links to the two
components. Assign the anchor tag that you want to add the route to the routerLink attribute.
Set the value of the attribute to the component to show when a user clicks on each link. Next,
update your component template to include <router-outlet>. This element informs Angular to
update the application view with the component for the selected route.
<h1>Angular Router App</h1>
<nav>
<ul>
<li><a routerLink="/first-component" routerLinkActive="active"
ariaCurrentWhenActive="page">First Component</a></li>
<li><a routerLink="/second-component" routerLinkActive="active"
ariaCurrentWhenActive="page">Second Component</a></li>
</ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>
Now, you can access first and second components using urls
**********************************************************************
UNIT-V
REACT
*********************************************************************
What is the importance of React
React is a JavaScript library for building user interfaces, primarily maintained by Facebook. It is
widely used in modern web development for building dynamic, responsive, and high-performance
web applications. Here’s why React is important:
Importance of React
1. Component-Based Architecture
React breaks the UI into reusable components.
Each component manages its own state and logic, which leads to modular, maintainable
code.
Encourages reusability, reducing development time.
2. Virtual DOM for Better Performance
React uses a Virtual DOM to track changes in the UI.
Instead of reloading the whole DOM, React efficiently updates only the changed parts,
improving performance.
3. Declarative UI
React allows developers to describe what the UI should look like for a given state.
Easier to debug and understand compared to imperative code.
4. Strong Community and Ecosystem
Massive support from Facebook, open-source contributors, and developers.
Rich ecosystem: tools like Redux, React Router, Next.js, etc., are widely used with React.
5. Unidirectional Data Flow
Data flows in a single direction (from parent to child), making the app easier to reason
about and debug.
6. JSX – JavaScript + HTML
React uses JSX, which allows writing HTML inside JavaScript.
Makes code more readable and expressive.
7. Cross-Platform Capabilities
With tools like React Native, you can build mobile apps for iOS and Android using the
same React principles.
8. SEO-Friendly
React (especially when used with server-side rendering tools like Next.js) improves SEO
compared to traditional JavaScript-heavy frameworks.
Use Cases
Single Page Applications (SPAs)
Dashboards
E-commerce websites
Social media platforms
Progressive Web Apps (PWAs)
******************************************************************
What is Virtual DOM
The Virtual DOM (V-DOM) is a core concept in React (and some other frameworks), designed to
improve the performance and efficiency of web applications by minimizing direct manipulations to
the real DOM.
DOM (Document Object Model) is a programming interface provided by browsers. It represents
the structure of your webpage as a tree of objects (called nodes), where each element in HTML
becomes a node.
Problem with Real DOM:
The real DOM is slow to update, especially when many changes are made.
Every DOM update triggers re-rendering, recalculating styles, reflowing layout, and
repainting the screen.
This slows down performance in complex, dynamic apps.
What is Virtual DOM?
Definition:
The Virtual DOM is an in-memory, lightweight JavaScript representation of the real DOM. It
allows React to perform updates more efficiently.
How Virtual DOM Works (Step-by-Step):
1. Initial Render:
React creates a Virtual DOM tree based on your components (JSX code).
It then renders the actual DOM for the first time.
2. State or Props Change:
When something changes (e.g., user input), React:
Creates a new Virtual DOM.
Compares it with the previous Virtual DOM (this is called diffing).
3. Diffing Algorithm:
React identifies the minimal set of changes needed.
It determines which elements actually changed and need to be updated in the real
DOM.
4. Efficient Update:
React updates only the changed parts in the real DOM (not the whole tree).
This makes the update fast and efficient.
******************************************************************
What are important files or folder structure of React
Key Files Explained
Application/
├── UI Elements → Reusable building blocks (buttons, inputs, cards)
├── Screens/Views → User-facing pages or route-based layouts
├── State Management → Data flow, global state, shared context
├── Data Layer → External communication (APIs, services, storage)
├── Behavior Logic → Business rules, custom logic, side effects
├── Utilities → Helpers, constants, formatters
├── Static Resources → Media, styles, themes, icons
├── Entry & Bootstrapping → App startup logic, mounting, configuration
File/Folder Purpose
public/index.html Main HTML file where React mounts (<div id="root">)
src/index.js Entry point, renders <App /> using ReactDOM
src/App.jsx Root React component
components/ Holds small, reusable components
pages/ Components mapped to routes (like Home, About)
services/ Functions for making API calls (e.g., using axios)
context/ For global state using React Context API
hooks/ Custom hooks like useFetch, useToggle
assets/ Static files like images, logos, fonts
styles/ CSS or SASS files, sometimes organized per component
******************************************************************
MERN – STACK – CREATING ENVIRONMENT
1. Create fullstack directory and go to that directory
2. Go to that directory and install node and npm
3. Create backend directory (all your server app files will be here) and run this command
npm init -y
4. In the same directory install express using this command npm install express
5. In the same directory install mongodb from official website and mongodb driver using npm
command.
6. Create server.js file in same directory and copy the below content to it. This is your actually http
server. You may have to add paths in it when ever you wanted to add server side applications and
access them through http request that is you need to define route.
const express = require('express');
const app = express();
const PORT = 3000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
run this server.js using node command. -- node server.js
7. Check whether you installed node correctly or not. Type the following command
node -v
8. check whether your nodes server is running correctly by starting it.
node server.js
Note:- in the same folder, you need to install mongodb driver and packages
npm install mongod -- driver
npm install mongodb -- packages
9. check whether your mongodb is installed correctly. Start its service by using following command
in linux --> sudo systemctl start mongod
in windows -- >net start MongoDB or goto services and start manually
To connect to mongodb, run command mongosh ( mongosh )
Installing REACT– Above 10 steps are common. Below are additional steps for react.
Now, come back to fullstack folder and create react-client folder and go to that folder.
1. Create Frontend-react-client folder, go to that folder and Install react.
npx create-react-app . ( “.” means use currect directory , i.e react-client folder)
2. Check wheter you have installed react perfectly by running this command
npm start
You can see that your app.js will execute automatically by this command and displayed the result in
localhost:3000 . This will start your client side development server. Dont confuse it with node
server. This is just temporary client server runs in clients memory.
Important – How react router works and how to route our own app called as myapp2
1. Inside same folder, install React Router. This will enable you to create more client app files and
route them through developement server.
npm install react-router-dom
2. To check whether you have installed react-router-dom perfectly then you create one app called
myapp2.js with following code
import React from 'react';
function Myapp2() {
return (
<div>
<h1>Hello, this is my own page in myapp2</h1>
</div>
);
}
export default Myapp2;
Now, add copy the following code in app.js. In which we address how to reach myapp2.
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Myapp2 from './myapp2';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<h1>Home Page</h1>} />
<Route path="/myapp2" element={<Myapp2 />} />
</Routes>
</Router>
);
}
export default App;
Now open localhost:3000/myapp2 , you should see Hello, this is my own page in myapp2 on the
web page.
Important Note :- Since you have reacts developments server and nodes backend server in same
machine, by default both take 3000 as default port. Change one of them, the best thing to change is
nodes servers port. Open server.js from your backend folder and change port value 3000 to 5000.
***********************************************************************
Write an application to insert student details in mongodb database using react, express and node.
1. Create reactjs file called Myreactdbform.js
import React, { useState } from 'react';
function Myreactdbform() {
const [studentId, setStudentId] = useState('');
const [studentName, setStudentName] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('http://localhost:5000/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ studentId, studentName }),
});
const result = await response.json();
if (result.success) {
setMessage('Student details successfully inserted');
setStudentId('');
setStudentName('');
} else {
setMessage('Insertion failed');
}
};
return (
<div style={{ padding: '20px' }}>
<h2>Enter Student Details</h2>
<form onSubmit={handleSubmit}>
<label>Student ID:</label>
<input
type="text"
value={studentId}
onChange={(e) => setStudentId(e.target.value)}
required
/><br /><br />
<label>Student Name:</label>
<input
type="text"
value={studentName}
onChange={(e) => setStudentName(e.target.value)}
required
/><br /><br />
<button type="submit">Submit</button>
</form>
<p>{message}</p>
</div>
);
}
export default Myreactdbform;
Run mongodb, server.js and react development server.. run your reactapp , you can successfully
insert values in mongodb.
************************************************************************