FSD2 Record - Final
FSD2 Record - Final
VATLURU, ELURU-534007
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING
This is to certify that this book is a bonafide record practical work done
in Full Stack Development – 2 Laboratory in I semester of III year B.Tech
COMPUTER SCIENCE AND ENGINEERING during academic year 2025-
2026.
Total Number of Experiments held :
Total Number of Experiments done :
Register Number :
EXTERNAL EXAMINER
INDEX
S.NO NAME OF THE DATE GRADE SIGN
EXPERIMENT
1 Typescript
a. Write a program to understand simple and
special types.
b. Write a program to understand function
parameter and return types.
c. Write a program to show the importance
with Arrow function, Use optional, default
and REST parameters.
d. Write a program to understand the
working of typescript with class,
constructor, properties, methods and
access specifiers.
e. Write a program to understand the
working of namespaces and modules.
f. Write a program to understand generics
with variables, functions and constraints.
2 Express JS – Routing, HTTP
Methods, Middleware.
a. Write a program to define a route,
Handling Routes, Route Parameters,
Query Parameters and URL building.
b. Write a program to accept data,
retrieve data and delete a specified
resource using http methods.
c. Write a program to show the working
of the middleware.
3 Express JS – Templating, Form Data
a. Write a program using templating
engine.
b. Write a program to work with
form data.
1.TypeScript
Program:
// SIMPLE TYPES
console.log("Number:", myNumber);
console.log("String:", myString);
console.log("Boolean:", myBoolean);
// SPECIAL TYPES
}
// 3. void - Function that returns nothing
logMessage();
// throwError();
OUTPUT
Number: 42
Boolean: true
Any (number): 10
Type Description
unknown Like any but forces you to check type before using
Program:
return a + b;
OUTPUT
Add: 8
Hello, Alice!
Is 10 even? true
c. write a program to show the importance with Arrow function. Use optional,
default and REST parameters.
Program:
};
};
};
// Output
console.log(greet()); // Hello!
console.log(multiply(5)); // 10 (5 * default 2)
console.log(multiply(5, 3)); // 15
console.log(sumAll(1, 2, 3)); // 6
OUTPUT
Hello!
Hello, Pavithra!
10
15
100
DESCRIPTION:
Program:
// Class definition
class Person {
// Constructor
this.name = name;
this.age = age;
this.gender = gender;
// Public method
}
// Private method
// Protected method
console.log(`Gender: ${this.gender}`);
// Subclass
this.grade = grade;
console.log(`Grade: ${this.grade}`);
// Create objects
student1.showDetails();
OUTPUT
My age is 20.
Grade: 9
Gender: Female
Program:
namespace MathOperations {
return a + b;
return a - b;
return a * b;
// Main program
class Demo {
console.log("Addition:", sum);
console.log("Subtraction:", difference);
console.log("Multiplication:", product);
console.log("Division:", quotient);
Demo.show();
Output:
Addition: 10
Subtraction: 6
Multiplication: 12
Division: 4
Program:
interface Box<T> {
value: T;
//Generic Function
console.log("Value:", item);
displayValue<number>(42);
displayValue<string>("TypeScript is powerful!");
displayValue<boolean>(true);
interface HasLength {
length: number;
console.log("Length:", item.length);
// Valid calls
Output:
Value: true
Length: 5
Length: 4
Length: 10
FSD – 2 Lab Record
EXPERIMENT – 2
1. Express JS – Routing, HTTP Methods, Middleware
Express.js is a minimal and flexible Node.js web application framework that provides a set of
features for building web and mobile applications easily. It simplifies the development of server-
side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.
Features of Express.js
Routing in Express.js
Routing in Express.js is the process of mapping to handle client requests.
Routing Flow
HTTP Request: Represents the incoming request with method and path (e.g., GET /users).
Route Matching: Lists all defined routes and determines which route matches the request.
Handler Execution: Executes the matching route’s handler function (req, res).
Sending Response: The server sends a response back to the client using methods like:
res.send()
res.json()
res.render()
Routing enables developers to configure endpoints for various paths and operations, such as:
Rendering views
Processing form data
Performing CRUD (Create, Read, Update, Delete) actions on resources
Syntax:
app.METHOD(PATH, HANDLER);
The GET method is used by a client to retrieve data from the server.
It takes two parameters: the URL to listen on and a callback function with req (client request) and
res (server response) as arguments.
Syntax:
1
FSD – 2 Lab Record
2. POST Method
The POST method sends data from the client to the server, usually to store it in a database.
It takes two parameters: the URL to listen on and a callback function with req (client request) and
res (server response). The data sent is available in the request body and must be parsed as JSON.
Syntax:
app.post("URL", (req, res) => {});
3. PUT Method
Syntax:
4. DELETE Method
The DELETE method removes data from the database.
It takes two parameters: the URL to listen on and a callback function with req (containing the ID of
the item to delete in the body) and res (server response).
Syntax:
app.delete("URL", (req, res) => {});
5. PATCH Method
Syntax:
3. node app.js
o Homepage:
http://localhost:3000/
3
FSD – 2 Lab Record
OUTPUT:
4
FSD – 2 Lab Record
2(a). Write a program to define a route, handle routes, route parameters, query parameters, and
URL building
Program:
5
FSD – 2 Lab Record
OUTPUT:
6
FSD – 2 Lab Record
2(b). Write a program to accept data, retrieve data, and delete a specified resource using
HTTP methods
Program:
app.use(express.json());
let items = [
{ id: 1, name: "Pen" },
{ id: 2, name: "Notebook" }
];
// GET – Retrieve
app.get('/items', (req, res) => {
res.json(items);
});
// DELETE – Delete by ID
app.delete('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(item => item.id !== id);
res.send(`Item with id ${id} deleted`);
});
7
FSD – 2 Lab Record
8
FSD – 2 Lab Record
Step 1: Start Your ServerSave your code in a file, for example: 1b.js
Run it in the Command Prompt using the following command:node 1b.js
You should see the message:App listening on http://localhost:3001
Step 2: Use curlBase URL:http://localhost:3001
A. GET /items – Retrieve all items
Method: GET URL: http://localhost:3001/items
No request body required.
Response:[
{ "id": 1, "name": "Pen" },
{ "id": 2, "name": "Notebook" }
]
B. POST /items – Add a new item
Method: POST URL: http://localhost:3001/items
Steps:Open another Command Prompt window.
Run the following command:curl -X POST http://localhost:3001/items -H "Content-Type:
application/json" -d "{\"name\":\"Marker\"}"
After running the command, open your browser and go to:http://localhost:3001/items
You should now see the third item ("Marker") added to the list.
C. DELETE /items/:id – Delete an item by ID
Method: DELETE Command:
curl -X DELETE http://localhost:3001/items/2URL: http://localhost:3001/items/2
(This deletes the item with ID = 2
9
FSD – 2 Lab
Record
OUTPUT:
10
FSD – 2 Lab
Record
Program:
Here’s a simple and clear example demonstrating how middleware works in Node.js using the
Express framework.
This program includes:
Global Middleware (runs on all requests)
Route-specific Middleware,Error-handling Middleware,Install Required Packages in Command
Prompt:
npm init -y
npm install express
const express = require('express');
const app = express(); const port = 3000;
// Global Middleware: Logs every request
app.use((req, res, next) => {
console.log(`[LOG] ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware/route
});
// Middleware to simulate authentication
const authMiddleware = (req, res, next) => {
const authorized = req.query.auth === 'true';
if (authorized) {
console.log('User is authenticated');
next();
} else {
res.status(401).send('Unauthorized access. Add ?auth=true to the URL.');
}};
// Route with no middleware
app.get('/', (req, res) => {
res.send('Welcome to the public route!');
});
// Route with authentication middleware
app.get('/secure', authMiddleware, (req, res) => {
res.send('Welcome to the secure route!');
});
// Route that throws an error
app.get('/error', (req, res, next) => {
next(new Error('Something went wrong!')); // Pass error to error-handling middleware
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(`[ERROR] ${err.message}`); res.status(500).send('Internal Server Error');
});
// Start the server
app.listen(port, () => {
console.log(`Middleware demo app running at
http://localhost:${port}`);});
11
FSD – 2 Lab
Record
OUTPUT:
12
FSD – 2 Lab
Record
EXPERIMENT – 3
3. Express JS – Templating, Form Data
// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Save as File name: Index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Welcome <%= user.name %></title>
</head>
<body>
<h1>Hello, <%= user.name %>!</h1>
<p>Age: <%= user.age %></p>
<h2>Hobbies:</h2>
<ul>
<% user.hobbies.forEach(function(hobby) { %>
<li><%= hobby %></li> <% }); %>
</ul>
</body>
</html>
13
FSD – 2 Lab
Record
OUTPUT:
14
FSD – 2 Lab
Record
15
FSD – 2 Lab
Record
OUTPUT:
16
FSD – 2 Lab Record
EXPERIMENT – 4
4. Express JS – Cookies, Sessions, Authentication
OUTPUT:
18
FSD – 2 Lab Record
Program:
OUTPUT:
20
FSD – 2 Lab Record
EXPERIMENT – 5
5. ExpressJS – Database, RESTful APIs
5a.Write a program to connect MongoDB database using Mongoose and perform CRUD operations
Program:
// 1. Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
// Create a user
async function createUser() {
const user = new User({
name: 'John Doe',
email: '[email protected]',
age: 30
});
const savedUser = await user.save();
console.log('User created:', savedUser);
}
21
FSD – 2 Lab Record
// Update a user by id
async function updateUser(userId) {
22
FSD – 2 Lab Record
23
FSD – 2 Lab Record
userId,
{ age: 35 },
{ new: true }
);
console.log('User updated:', updatedUser);
}
// Delete a user by id
async function deleteUser(userId) {
const deletedUser = await User.findByIdAndDelete(userId);
console.log('User deleted:', deletedUser);
}
mongoose.connection.close();
}
run();
24
FSD – 2 Lab Record
OUTPUT:
Execution:
25
FSD – 2 Lab Record
Program:
// Step 1: Backend REST API (Express)
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
let items = [
{ id: 1, name: "Item One" },
{ id: 2, name: "Item Two" }
];
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Create new item
app.post('/api/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// Update an item by id
app.put('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = items.find(i => i.id === id);
if (item) {
item.name = req.body.name;
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// Delete an item by id
app.delete('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(i => i.id !== id);
res.status(204).end();
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`); });
26
FSD – 2 Lab Record
OUTPUT:
Execution:
1. Run the backend: node server.js
2. Open index.html in your browser (just double click or serve via live-server)
3. You get a SPA with Add, Edit, Delete functionality using RESTful API calls!
27
FSD – 2 Lab Record
<ul id="itemsList"></ul>
<script>
const apiUrl = 'http://localhost:3000/api/items';
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name; // Edit button
const editBtn = document.createElement('button');
28
FSD – 2 Lab Record
29
FSD – 2 Lab Record
editBtn.textContent = 'Edit';
editBtn.onclick = () => editItem(item.id, item.name);
// Delete button
const delBtn = document.createElement('button');
delBtn.textContent = 'Delete';
delBtn.onclick = () => deleteItem(item.id);
li.appendChild(editBtn);
li.appendChild(delBtn);
list.appendChild(li);
});
} // Add a new item
async function addItem() {
const input = document.getElementById('itemName');
const name = input.value.trim();
if (!name) return alert('Please enter a name');await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});
input.value = '';
fetchItems();
} // Edit an item
async function editItem(id, oldName) {
const newName = prompt('Edit item name:', oldName);
if (!newName) return;
await fetch(`${apiUrl}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName })
});
fetchItems();
}
// Delete an item
async function deleteItem(id) {
await fetch(`${apiUrl}/${id}`, { method: 'DELETE' });
fetchItems();
}
// Initial load
fetchItems();
</script></body></html>
30
FSD – 2 Lab Record
Output:
easy
31
FSD – 2 Lab Record
EXPERIMENT - 6
6. ReactJS – Render HTML, JSX, Components – function & Class
Uses of ReactJS
ReactJS is mainly used for Front-End Development. Examples:
1. Single Page Applications (SPA) – like Gmail, Facebook, Instagram.
2. Dynamic Websites – live content updates without page reload.
3. Cross-Platform Development – with React Native
4. , you can build mobile apps for Android C iOS using the same React code.
5. Dashboards and Data-Driven Apps – real-time updates, charts, analytics.
6. E-commerce Sites – product pages that update instantly.
32
FSD – 2 Lab Record
33
FSD – 2 Lab Record
34
FSD – 2 Lab Record
35
FSD – 2 Lab Record
OUTPUT:
Welcome to ReactJS Current Year: 2025
2+3=5
36
FSD – 2 Lab Record
37
FSD – 2 Lab Record
OUTPUT:
Main App Component
Hello from Greeting Component!
38
FSD – 2 Lab Record
39
FSD – 2 Lab Record
OUTPUT:
40
FSD – 2 Lab Record
EXPERIMENT – 7
7. ReactJS – Props and States, Styles, Respond to Events
(a) Program to Work with Props and State
Theory:
Props (Properties)
Definition: Props are inputs to a React component.
Nature: Read-only (cannot be modified inside the component).
Purpose: Used to pass data from parent to child component.
Analogy: Props are like function parameters.
State
Definition: State represents data that belongs to a component and can change over time.
Nature: Mutable (can be updated).
Purpose: Used to manage data that changes when the user interacts (e.g., button clicks, typing).
Analogy: State is like a component’s personal memory.
Program:
import React, { useState } from "react";
return (
<div>
<h1>React Props and State Example</h1>
{/* Passing props */}
<ChildComponent name="Bhargavi" age={age} />
<button onClick={() => setAge(age + 1)}>Increase Age</button>
</div>
);
}
41
FSD – 2 Lab Record
OUTPUT:
42
FSD – 2 Lab Record
Theory:
Program (App.js):
return (
<div>
<h1 style={{ textAlign: "center", color: "purple" }}>
React Styling Example
</h1>
43
FSD – 2 Lab Record
OUTPUT:
44
FSD – 2 Lab Record
Program (App.js):
import React, { useState } from "react";
function App() {
const [message, setMessage] = useState("Click the button!");
function handleClick() {
setMessage("Button was clicked!");
}
function handleInput(event) {
setMessage("You typed: " + event.target.value);
}
return (
<div>
<h1>React Event Handling Example</h1>
<p>{message}</p>
45
FSD – 2 Lab Record
OUTPUT:
46
FSD – 2 Lab Record
EXPERIMENT – 8
8. ReactJS – Conditional Rendering, Rendering Lists, React Forms
a. Program for Conditional Rendering
Theory:
Conditional Rendering in React means displaying different components or
elements based on specific conditions — just like using if, else, or switch statements in JavaScript.
React automatically updates the UI when state or props change,
which makes conditional rendering ideal for creating interactive and dynamic interfaces.
Common Techniques for Conditional Rendering:
1. Ternary Operator
Syntax:
2. condition ? <ComponentA /> : <ComponentB />
Example: Render one element if a user is logged in, and another if not.
3. Logical AND (GG)
Syntax:
4. condition CC <Component />
Example: Render an element only when the condition is true.
5. if–else Statements
Used outside of JSX to determine which component to return.
Program (ConditionalRendering.js):
import React, { useState } from 'react';
function ConditionalRendering() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, User!</h1>
):(
<h1>Please log in to continue.</h1>
)}
47
FSD – 2 Lab Record
OUTPUT:
48
FSD – 2 Lab Record
function RenderList() {
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
return (
<div>
<h1>Fruits List</h1>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
}
49
FSD – 2 Lab Record
OUTPUT:
50
FSD – 2 Lab Record
C. Program for Working with Different Form Fields using React Forms
Theory:
In React, forms are managed using controlled components.
A controlled component is an input element (like <input>, <textarea>, <select>) whose value is
controlled by React state.
This allows developers to manage, validate, and handle user inputs effectively in real time.
Key Concepts:
1. Controlled Components:
The value of form elements is tied to React’s state.
Example:
<input type="text" value={username} onChange={handleChange} />
2. State Management:
o Form data is stored in a single state object.
o Updated dynamically using event handlers.
3. Event Handling:
o onChange: Updates state when the user types or selects input.
o onSubmit: Handles form submission and prevents page reload.
4. Advantages:
o Full control over form inputs.
o Easy validation and data manipulation.
o Predictable and reactive form behavior.
Program (ReactForms.js):
import React, { useState } from 'react';
function ReactForms() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
51
FSD – 2 Lab Record
52
FSD – 2 Lab Record
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
53
FSD – 2 Lab Record
output:
Execution process:
Open http://localhost:3000
54
FSD – 2 Lab Record
EXPERIMENT – 9
55
FSD – 2 Lab Record
56
FSD – 2 Lab Record
<Link to="/contact">Contact</Link>
</nav>
57
FSD – 2 Lab Record
OUTPUT:
Steps to Run
58
FSD – 2 Lab Record
In React, the screen updates automatically whenever the state or props of a component
change.
This is achieved using React’s virtual DOM → only the changed part of UI re-renders.
When to Use
React Router: When building applications with multiple pages like Home, About, Contact.
Updating Screen: When creating interactive UIs (counters, forms, live data, etc.) where values
change dynamically.
Program:
// App.js
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>React State Update Example</h1>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>+ Increase</button>
<button onClick={() => setCount(count - 1)}>— Decrease</button>
<button onClick={() => s e t C o u n t ( 0 ) } > ■³
– Reset</button>
</div>
);
}
export default App;
59
FSD – 2 Lab Record
OUTPUT:
Execution Steps
1. Create project:
3. cd myapp
2. Run:
2. npm start
3. Open http://localhost:3000.
o Initially count = 0.
o Click Increase → count updates. Click Decrease → count reduces.
60
FSD – 2 Lab Record
EXPERIMENT – 10
10. ReactJS – Hooks, Sharing Data Between Components
a) Program to Understand Importance of Using Hooks
What is a Hook in React?
A Hook is a special function in React that lets you use state and other React features in
functional components (without writing class components).
Examples:
o useState → for state management
o useEffect → for side effects (API calls, timers, etc.)
o useContext → for sharing data globally
o useRef, useReducer, etc.
How to Use Hooks?
1. Import from React:
2. import React, { useState } from "react";
3. Call inside a functional component:
4. const [count, setCount] = useState(0);
o count → variable (state)
o setCount → function to update the variable
5. Update state using setCount → causes re-render of UI.
When to Use Hooks?
When you need to store and update data inside a component (like form inputs, counters,
toggles).
When you want to fetch or update data automatically when a component mounts (using
useEffect).
When you need to reuse logic between multiple components.
Program:
import React, { useState } from "react";
function App() {
// useState Hook: count is variable, setCount is function to update it
const [count, setCount] = useState(0);
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>React useState Hook Example</h1>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)}>Decrease</button>
</div>
);
}
61
FSD – 2 Lab Record
OUTPUT:
62
FSD – 2 Lab Record
63
FSD – 2 Lab Record
OUTPUT:
64
FSD – 2 Lab Record
EXPERIMENT-11
Program:
src/App.js:
import React, { useState } from 'react';
import './App.css';
function App() {
// State variables
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
<ul>
65
FSD – 2 Lab Record
src/App.css:
.App {
text-align: center;
margin-top: 50px;
font-family: Arial, sans-serif;
}
.input-container {
margin-bottom: 20px;
}
input {
padding: 10px;
width: 250px;
font-size: 16px;
}
button {
padding: 10px 15px;
margin-left: 10px;
font-size: 16px;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
max-width: 300px;
margin: 0 auto;
text-align: left;
}
li {
display: flex;
66
FSD – 2 Lab Record
justify-content: space-between;
background: #f0f0f0;
padding: 8px;
margin-bottom: 10px;
border-radius: 4px;
}
.delete-btn {
background: red;
color: white;
border: none;
cursor: pointer;
}
Execution process:
1) open command prompt
i) npx create-react-app todo-app
ii) cd todo-app
iii) npm start
2) open your folder in vs code
3) replace src/App.js and src/App.css from above codes
67
FSD – 2 Lab Record
OUTPUT:
68
FSD – 2 Lab Record
EXPERIMENT – 12
12. MongoDB – Installation, Configuration, CRUD Operations
db.students.insertOne({
name: "Alice", age: 20, course: "Math"
70
FSD – 2 Lab Record
OUTPUT:
71
FSD – 2 Lab Record
);
Insert multiple documents
db.students.insertMany([
{ name: "Bob", age: 22, course: "Science" }, { name: "Carol", age: 21, course: "English" }
]);
2. Read (Find Documents)
Find all documents
db.students.find();
Find one document
db.students.findOne({ name: "Alice" });
Find with condition
db.students.find({ age: { $gt: 20 } });
3. Update (Modify Documents)
Update one document
db.students.updateOne(
{ name: "Alice" },
{ $set: { course: "Computer Science" } }
);
Update multiple documents
db.students.updateMany(
{ age: { $gt: 20 } },
{ $set: { status: "Senior" } }
);
4. Delete (Remove Documents)
Delete one document
db.students.deleteOne({ name: "Bob" });
Delete multiple documents
db.students.deleteMany({ age: { $lt: 21 } });
72
FSD – 2 Lab Record
OUTPUT
OUTPUT:
73
FSD – 2 Lab Record
3. Update Documents
Update one document
db.students.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 21 } } // Update
);
74
FSD – 2 Lab Record
Output :
75
FSD – 2 Lab Record
EXPERIMENT – 13
13. MongoDB – Databases, Collections, and Records
a. Write MongoDB queries to Create and Drop Databases and Collections
Concept Overview:
A database is a container for collections.
A collection is a container for documents (equivalent to tables in SǪL).
A document is a single record (in JSON format).
1. Creating a Database
In MongoDB, you don’t explicitly create a database. When you insert a
document into a collection in a non-existing database, it is automatically created.
use myDatabase;
// Switches to or creates the database
show dbs;
// Lists all databases
2. Creating a Collection
You can create a collection explicitly using the createCollection() method or automatically by
inserting a document into a new collection.
// Syntax
db.createCollection("students");
3. Dropping a Collection
You can remove an existing collection from the database using the drop() method.
// Delete the 'students' collection
db.students.drop();
4. Dropping a Database
To delete an entire database, first switch to it using the use command, then call db.dropDatabase().
use myDatabase; // Switch to the database
76
FSD – 2 Lab Record
output:
77
FSD – 2 Lab Record
78
FSD – 2 Lab Record
79
FSD – 2 Lab Record
EXPERIMENT – 14
14. Augmented Programs: (Any 2 must be completed)
a. Design a To-Do List Application using NodeJS and ExpressJS
Objective
To design a simple To-Do List application using Node.js, Express.js, and MongoDB that performs
CRUD operations.
Concept Overview
A To-Do List App is a beginner-level project that helps understand:
RESTful API development
ExpressJS routing
CRUD operations using MongoDB
Project Requirements
Backend: Node.js + Express.js
Database: MongoDB (Local or Atlas)
Features:
Add a Task
View All Tasks
Mark Task as Complete
Delete Task
Step-by-Step Implementation
1. Folder Structure and Project Setup
mkdir todo-app
cd todo-app
npm init -y
npm install express mongoose body-parser
2. Connect to MongoDB (Atlas or Local) — app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const taskRoutes = require('./routes/taskRoutes');
const app = express();
app.use(bodyParser.json());
// MongoDB Connection
mongoose.connect('mongodb://127.0.0.1:27017/todoDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use('/tasks', taskRoutes);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
3. Create Mongoose Schema — models/Task.js
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({ title: String, completed: {
80
FSD – 2 Lab Record
81
FSD – 2 Lab Record
type: Boolean,
default: false
}
});
// Create Task
router.post('/', async (req, res) => {
const task = new Task(req.body);
await task.save();
res.send(task);
});
// Delete Task
router.delete('/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send({ message: 'Task deleted' });
});
module.exports = router;
82
FSD – 2 Lab Record
OUTPUT:
83
FSD – 2 Lab Record
const questions = [
{
question: "What is the capital of France?",
options: ["Paris", "London", "Berlin", "Madrid"],
answer: "Paris"
},
{
question: "What is 2 + 2?",
options: ["3", "4", "5", "6"],
answer: "4"
},
{
question: "Who wrote 'Hamlet'?",
options: ["Shakespeare", "Tolstoy", "Homer", "Dante"],
answer: "Shakespeare"
}
];
function App() {
const [current, setCurrent] = useState(0);
const [score, setScore] = useState(0);
const [showScore, setShowScore] = useState(false);
return (
<div style={{ padding: '30px', textAlign: 'center' }}>
{showScore ? ( <h2>You scored {score} out of {questions.length}</h2> ):(
84
FSD – 2 Lab Record
85
FSD – 2 Lab Record
<>
<h3>{questions[current].question}</h3>
{questions[current].options.map((opt, index) => (
<button
key={index}
onClick={() => handleAnswer(opt)}
style={{
display: 'block',
margin: '10px auto',
padding: '10px 20px',
backgroundColor: '#4CAF50',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
{opt}
</button>
))}
</>
)}
</div>
);
}
86
FSD – 2 Lab Record
87