Full Stack Development Lab
Full Stack Development Lab
LAB-2
HOW TO INSTALL VISUAL STUDIO CODE ON
WINDOWS?
→ Steps to install visual studio code on windows :
STEP: 1 Visit the official website VISUAL STUDIO CODE and using any web
browser like GOOGLE CHROME and MICROSOFT EDGE, etc..,
STEP:2 Press the “DOWNLOAD FOR WINDOWS” button on the website to start
the download of the visual studio code application.
STEP: 3 when the download finishes, then the VISUAL STUDIO CODE ICON
appears in the downloads folder.
STEP: 4 Click on the installer icon to start the installation process of the visual
studio code.
STEP: 5 After the installer opens, it will ask you to accept the terms and conditions
of the visual studio code. Click on I accept the agreement and then click the next
button.
STEP:6
Choose the location data for running the visual studio code. It will then ask you to
browse the location. Then click the next button.
STEP:7
Then it will ask to begin the installation setup. Click on the install button.
STEP:8
After clicking on Install, it will take about 1 minute to install the Visual Studio Code
on your device.
STEP:9
After the Installation setup for Visual Studio Code is finished, it will show a
window like this below. Tick the "Launch Visual Studio Code" checkbox and then
click Next.
STEP: 10 After the previous step, the Visual Studio Code window opens
successfully. Now you can create a new file in the Visual Studio Code window and
choose a language of yours to begin your programming journey
INSTALLATION PROCESS ON NODE.JS :
How to Install Node.js on Windows
Installing Node.js on Windows is a straightforward process, but it's essential to follow
the right steps to ensure smooth setup and proper functioning of Node Package
Manager (NPM), which is crucial for managing dependencies and packages. This
guide will walk you through the official site, NVM, Windows Subsystem, and
Package Manager for Windows 7, 8, 10, and 11.
Method 1: Use the Official Website
Follow these steps to install the Node.js on your Windows:
C:\Users\Admin> node -v
Windows Subsystem for Linux (WSL) is a great option for those who prefer
a Linux environment. You can run a Linux distribution on your Windows machine
and use Linux tools like apt-get for installation.
This will install the WSL feature and the default Ubuntu distribution.
Step 2: Set up a Linux Distribution
Once WSL is installed, launch the Ubuntu (or another Linux distro) app from
the Start Menu and set up your Linux distribution by creating a user and password.
Open the WSL terminal (Ubuntu or your chosen distribution) and update your
package list:
sudo apt update
Once the update is done, Install Node.js using the following command:
sudo apt install nodejs
sudo apt install npm
Once the installation is complete, verify the installation by entering the following
command:
node -v
npm -v
Method 4: Install Node.js & NPM using WPM
Windows 10 and 11 users can use winget, the Windows Package Manager, to easily
install Node.js.
→ Verify Installation for Node.js and NPM
After installation, check if Node.js is installed correctly:
node -v
npm -v
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
// server.js
const http = require("http");
How to run:
1. Save as server.js.
2. Run: node server.js
3. Then open a browser at http://localhost:3000 and you see "Hello, World!".
// express-hello.js
res.send("Hello, World!");
});
app.listen(port, () => {
});
npm init -y
npm install express
2.Then run: node express-hello.js
1. Routing in Express.js
Routing defines how your Express app responds to client requests for specific
endpoints (paths and methods).
res.send("Home Page");
});
res.send("About Page");
});
2. HTTP Methods in Express.js
res.send("Form submitted");
});
});
});
3. Middleware in Express.js
Middleware are functions that run during the lifecycle of a request to the server.
They can: 1. Modify request/response objects
// Global middleware
console.log(`${req.method} ${req.url}`);
});
// 2. Route Parameters
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
// 3. Query Parameters
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
res.send(`Search term: ${searchTerm}`);
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
OUTPUTS:
// server.js
const express = require('express');
const app = express();
app.use(express.json()); // parse JSON bodies
Output:
1. POST /items — Add data
Request:
http
CopyEdit
POST /items HTTP/1.1
Content-Type: application/json
{
"name": "Laptop"
}
Response:
json
CopyEdit
{
"id": 1,
"name": "Laptop"}
json
CopyEdit
{
"name": "Phone"}
Response:
json
CopyEdit
{
"id": 2,
"name": "Phone"}
OUTPUT :
Visit the home page: Hello, this is the main route!
2. Express JS – Templating, Form Data
Express.js facilitates both templating for dynamic HTML generation and handling
form data submitted from clients.
1. Templating in Express.js:
Purpose : Templating engines allow embedding dynamic data and logic within static
HTML structures, generating personalized content for users.
Common engines: Popular choices include Ejs (Embedded JavaScript), Pug (formely
jade), and Handlebars.
Setup:
1. Install the desired templating engine (e.g., npm install ejs).
2. Configure Express to use the engine: app.set('view engine', 'ejs');
3. Specify the directory where your template files are located: app.set('views',
path.join(__dirname, 'views'));
// Specify the directory where your EJS templates (views) are located
app.set(‘views’, path.join(__dirname, ‘views’));
Output:
User Information
coding
reading
hiking
// Start server
app.listen(3000, () => {
console.log(“Server is running on http://localhost:3000”);
});
OUTPUT:
Form Example
Name: [__________]
Email: [_________]
[Submit]
After filling and submitting:
Received data:
Name: Disney
Email: [email protected]
Explanation:
express-session:
This middleware creates and manages sessions. It assigns a unique session ID to each
user and stores session data on the server (or a chosen session store).
cookie-parser:
This middleware parses incoming request cookies, making them accessible via
req.cookies.
Session ID Cookie:
express-session automatically sets a session ID cookie (typically named connect.sid)
in the user's browser, which is used to identify the session on subsequent requests.
secret:
A crucial security measure, used to sign the session ID cookie, preventing tampering.
secure and httpOnly cookie options:
Enhance security by ensuring the cookie is only sent over HTTPS and cannot be
accessed by client-side JavaScript, respectively.
req.session:
This object is provided by express-session and allows you to store and retrieve
session-specific data.
isAuthenticated middleware:
A common pattern to protect routes, ensuring only authenticated users can access
them.
req.session.destroy():
Used to end a session and remove its data from the session store.
res.clearCookie():
Removes the session ID cookie from the client's browser.
// Middleware
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
// Configure session
app.use(session({
secret: 'mysecretkey123', // Secret for signing the session ID cookie
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // Session expires after 1 minute
}));
// Homepage
app.get('/', (req, res) => {
if (req.session.username) {
res.send(`<h2>Welcome back, ${req.session.username}!</h2>
<a href="/logout">Logout</a>`);
} else {
res.send(`<form method="POST" action="/login">
<input type="text" name="username" placeholder="Enter username"
required />
<button type="submit">Login</button>
</form>`);
}
});
// Login handler
app.post('/login', (req, res) => {
const username = req.body.username;
req.session.username = username;
res.cookie('user', username); // Set a cookie
res.redirect('/');
});
// Logout handler
app.get('/logout', (req, res) => {
res.clearCookie('user'); // Clear cookie
req.session.destroy(); // Destroy session
res.redirect('/');
});
// Start server
app.listen(3000, () => {
console.log(“Server is running on http://localhost:3000")
});
OUTPUT:
Enter username: cartoon
login
Welcome back, cartoon
Logout
// Hash the user’s password once (in real apps, this would be stored already)
bcrypt.hash(‘1234’, 10, (err, hash) => {
users[0].passwordhash = hash;
});
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: ‘secretkey123’,
resave: false,
saveunitialized: false
}));
/ Routes
app.get('/', (req, res) => {
if (req.session.userId) {
res.send(<h2>Welcome, ${req.session.username}!</h2><a
href="/logout">Logout</a>);
} else {
res.send(`<form method="POST" action="/login">
<input name="username" placeholder="Username" required />
<input name="password" type="password" placeholder="Password"
required />
<button type="submit">Login</button>
</form>`);
}
});
app.listen(3000, () => {
console.log(Server running on http://localhost:3000);
});
OUTPUT:
Username:
Password:
Login
// MongoDB connection
mongoose.connect(‘mongodb://localhost:27017/mydb’, {
useNewUrlparser: true,
useUnifiedTopology: true
})
.then(() => console.log(‘ MongoDB connected’))
.catch(err => console.log(‘ MongoDB connection error:’, err));
// CREATE
app.post(‘/users’, async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.send(user);
} catch (err) {
res.status(400).send(err);
}
});
// READ ONE
app.get(‘/users/:id’, async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).send(‘User not found’);
res.send(user);
} catch (err) {
res.status(400).send(err);
}
});
// UPDATE
app.pu(‘/users/:id’, async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!user) return res.status(404).send(‘User not found’);
res.send(user);
} catch (err) {
res.status(400).send(err);
}
});
// DELETE
app.delete(‘/users/:id’, async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) return res.status(404).send(‘User not found’);
res.send(‘User deleted’);
} catch (err) {
res.status(400).send(err);
}
});
// Start Server
app.listen(3000, () => {
console.log(‘Server is running on http://localhost:3000’);
});
Index.html:
<!DOCTYPE html>
<html>
<title>Test SPA</title>
</head>
<body>
<h1>Hello from index.html!</h1>
</body>
</html>
server.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
app.use(express.static('public'));
// Create
app.post('/api/users', (req, res) => {
const user = req.body;
user.push(user);
res.status(201).json({ message: 'User added', user });
});
// Start server
app.listen(3000, () =>
console.log('Server is running on http://localhost:3000')
);
OUTPUT:
Hello from index.html
npm start
Folder structure:
my-html-app
|-----index.js
|-----public/
| |-----index.html
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
<p>This HTML page is rendered using Express server.</p>
</body>
</html>
Index.js:
Folder Structure:
Waiting-markup-app/
|------public/
| |------index.html
| |------bundle.js
|---------src/
| |-----App.jsx
|--------server.js
|--------webpack.config.js
|-------- .babelrc
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Waiting Markup</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
bundle.js:
document.getElementById("root").innerHTML = "<h1>Hello, this is my
output!</h1>";
App.jsx:
// src/App.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
.babelrc:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
webpack.config.js:
module.exports = {
entry: './src/App.jsx',
output: {
path: path.resolve(__dirname, 'public/'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
mode: 'development'
};
server.js:
app.use(webpackMiddleware(compiler));
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Folder structure:
My-node-app/
│
├── index.js
└── components/
├── Layout.js
└── Content.js
My-node-app/ Index.js:
module.exports = {
Header,
Footer
};
My-node-app/components/content.js:
render() {
console.log("Rendering Content...");
console.log(this.message);
this.renderNestedComponent();
}
render() {
console.log("Rendering Sidebar...");
console.log(this.info);
}
}
Output:
Rendering App...
Rendering Header...
Rendering Content...
This is the main content area.
Rendering Sidebar...
Sidebar info here.
Rendering Footer...
for frontend:
Folder structure:
my-app/
├── backend/
│ └── server.js
├── frontend/
│ ├── public/
│ │ └── index.html
│ ├── src/
│ │ ├── App.jsx
│ │ └── index.js
└── package.json
backend/ server.js:
const express = require('express');
const cors = require('cors');
app.use(cors());
app.listen(5000, () => {
console.log(`Backend running on http://localhost:5000`);
});
frontend/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
frontend/src/App.jsx:
useEffect(() => {
fetch('http://localhost:5000/api/message')
.then(res => res.json())
.then(data => setMessage(data.message))
.catch(err => console.error(err));
}, []);
return (
<div>
<h1>React Frontend</h1>
<p>{message ? message : "Loading..."}</p>
</div>
);
};
frontend/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
frontend/package.json:
{
"name": "frontend",
"version": "0.1.0",
"private": "true",
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.1"
},
"scripts": {
"start": "react-scripts start"
},
"proxy": "http://localhost:5000"
}
Output:
b) Write a program to add styles (CSS & Sass Styling) and display
data.
Folder structure:
node-css-sass-app/
├── public/
│ ├── styles/
│ │ ├── main.scss
├── views/
│ └── index.ejs
├── app.js
Install packages:
npm init -y
npm install express ejs
npm install sass-middleware
node-css-sass-app/public/styles/main.scss:
$primary-color: #3498db;
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
h1 {
color: $primary-color;
}
ul {
list-style: none;
padding: 0;
li {
background: white;
margin: 10px 0;
padding: 10px;
border-left: 5px solid $primary-color;
}
}
}
node-css-sass-app/views/index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Styled Node App</title>
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<h1>Data List</h1>
<ul>
<% data.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
</body>
</html>
node-css-sass-app/app.js:
// Sass middleware
app.use(
sassMiddleware({
src: path.join(__dirname, 'public', 'styles'),
dest: path.join(__dirname, 'public', 'styles'),
debug: true,
outputStyle: 'compressed',
prefix: '/styles',
})
);
// Static files
app.use(express.static(path.join(__dirname, 'public')));
// Sample data
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
// Routes
app.get('/', (req, res) => {
res.render('index', { data });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output :
+------------------------------+
| Data List | ← blue heading
| |
| ┌────────────────────────┐ |
| | Apple | | ← white box with blue border
| └────────────────────────┘ |
| ┌────────────────────────┐ |
| | Banana | |
| └────────────────────────┘ |
| ... |
+------------------------------+
Output:
Folder structure:
project/
├── views/
│ └── index.ejs
├── server.js
└── package.json
server.js:
res.render('index', {
user: {
name: 'John Doe',
role: 'admin',
},
isLoggedIn: isLoggedIn
});
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Conditional Rendering</title>
</head>
<body>
<% if (isLoggedIn) { %>
<h1>Welcome, <%= user.name %>!</h1>
<% if (user.role === 'admin') { %>
<p>You have admin privileges.</p>
<% } else { %>
<p>You are a regular user.</p>
<% } %>
<% } else { %>
<h1>Please log in to continue.</h1>
<% } %>
</body>
</html>
Package.json:
{
"name": "conditional-rendering",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"ejs": "^3.1.10",
"express": "^4.21.2"
},
"description": "",
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
Outputs:
Output 1:
isLoggedIn is true:
isLoggedIn = true
user.role = 'admin'
Output 2:
isLoggedIn = false:
Please log in to continue.
/node-list-rendering
├── views
│ └── users.ejs
└── app.js
node-list-rendering/views/users.ejs:
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
node-list-rendering/app.js:
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% users.forEach(function(user) { %>
<li><strong><%= user.name %></strong> - Age: <%= user.age %></li>
<% }); %>
</ul>
</body>
</html>
List of Users
- Alice - Age: 25
- Bob - Age: 30
- Charlie - Age: 28
c) Write a program for working with different form fields using react
forms.
Folder Structure:
form-app/
├── server/ <-- Node.js + Express backend
│ └── index.js
├── client/ <-- React frontend
│ ├── src/
│ │ └── App.js
│ └── package.json
form-app/server/index.js:
app.use(cors());
app.use(bodyParser.json());
// GET route
app.get('/', (req, res) => {
res.send('Server is up and running!');
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Install packages:
npm init -y
npm install express cors body-parser
node index.js
form-app/client/src/App.js:
function App() {
return (
<div className="container">
{/* App Logo */}
<div className="logo-container">
<img src="/mylogo.png" alt="App Logo" className="logo" />
</div>
form-app/client/package.json:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.4",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Output:
Name:
Email:
Passwor
d:
Submit
my-react-router-app/
│
├── public/
│ └── index.html
├── src/
│ ├── App.js
│ ├── Home.js
│ ├── About.js
│ ├── Contact.js
│ └── index.js
├── package.json
my-react-router-app/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>React Router App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
my-react-router-app/src/App.js:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
}
my-react-router-app/src/Home.js:
import React from 'react';
function Home() {
return (
<div>
<h1>Welcome to My Website</h1>
<p>This is a simple React Router demo app.</p>
</div>
);
}
my-react-router-app/src/About.js:
function About() {
return (
<div>
<h1>About This App</h1>
<p>This app demonstrates routing in React using React Router.</p>
<p>Built with 😆 by OpenAI and you!</p>
</div>
);
}
my-react-router-app/src/contact.js:
function Contact() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
return (
<div>
<h1>Contact Us</h1>
{submitted ? (
<p style={{ color: 'green' }}>
✅ Thank you, <strong>{formData.name}</strong>! Your message has been
sent.
</p>
):(
<form onSubmit={handleSubmit}>
<label>Name:</label><br />
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/><br /><br />
<label>Email:</label><br />
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/><br /><br />
<label>Message:</label><br />
<textarea
name="message"
value={formData.message}
onChange={handleChange}
required
rows="4"
></textarea><br /><br />
<button type="submit">Send</button>
</form>
)}
</div>
);
}
my-react-router-app/src/index.js:
my-react-router-app/package.json:
{
"name": "my-react-router-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.30.1",
"react-scripts": "^0.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Output:
Contact: Contact Us
Name:
Email:
Message:
Send
function updateScreen() {
readline.cursorTo(process.stdout, 0, 0); // Move cursor to top-left
readline.clearScreenDown(process.stdout); // Clear screen
// Initial update
updateScreen();
Output:
📅 Current Time:
4:51:38 pm
Install package:
//file: mongoose-hooks-example.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/hookDemo', {
useNewUrlParser: true,
useUnifiedTopology: true
});
Folder structure:
node-shared-data-example
├── sharedData.js
├── writer.js
├── reader.js
└── main.js
node-shared-data-example/sharedData.js:
// sharedData.js
const data = {
message: "Initial message"
};
module.exports = {
getMessage: () => data.message,
setMessage: (newMessage) => {
data.message = newMessage;
}
};
node-shared-data-example/writer.js:
// writer.js
const sharedData = require('./sharedData');
function updateMessage() {
sharedData.setMessage("Updated by writer module");
console.log("✅ Message updated in writer");
}
module.exports = updateMessage;
node-shared-data-example/reader.js:
// reader.js
const sharedData = require('./sharedData');
function readMessage() {
console.log("📩 Reader got message:", sharedData.getMessage());
}
module.exports = readMessage;
node-shared-data-example/main.js:
// main.js
const updateMessage = require('./writer');
const readMessage = require('./reader');
Output:
Before update:
📩 Reader got message: Initial message
🔹 Updating message...
✅ Message updated in writer
🔹 After update:
📩 Reader got message: Updated by writer module
Go to Network Access
Click Add IP Address
Choose 0.0.0.0 (allow from anywhere — for dev only!)
Or your IP for security
mongodb+srv://username:<password>@cluster0.xxxxx.mongodb.net/database_name?
retryWrites=true&w=majority
Folder structure:
mongo-node-crud
|-------- .env
|-------- sever.js
mongo-node-crud/server.js:
app.use(express.json());
mongo-node-crud/ .env :
MONGO_URI=mongodb+srv://admin:[email protected]/
testdb?retryWrites=true&w=majority
PORT=5000
mongo-native-crud
|----- .env
|----- crud.js
mongo-native-crud/crud.js:
require('dotenv').config();
const { MongoClient, ObjectId } = require('mongodb');
try {
await client.connect();
console.log('✅ Connected to MongoDB');
const db = client.db(dbName);
const users = db.collection('users');
// ----------------------------
// 🔽 INSERT - insertOne()
// ----------------------------
const newUser = { name: 'Alice', email: '[email protected]', age: 25 };
const insertResult = await users.insertOne(newUser);
console.log('✅ Inserted:', insertResult.insertedId);
// ----------------------------
// 🔍 READ - find()
// ----------------------------
const allUsers = await users.find().toArray();
console.log('📄 All Users:', allUsers);
// ----------------------------
// ✏️UPDATE - updateOne()
// ----------------------------
const updateResult = await users.updateOne(
{ _id: insertResult.insertedId },
{ $set: { age: 30 } }
);
console.log('✏️Updated:', updateResult.modifiedCount, 'document(s)');
// ----------------------------
// ❌ DELETE - remove() is deprecated, use deleteOne()
// ----------------------------
const deleteResult = await users.deleteOne({ _id: insertResult.insertedId });
console.log(' Deleted:', deleteResult.deletedCount, 'document(s)');
} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('🔌 Disconnected');
}
}
main();
mongo-native-crud/ .env:
MONGO_URI=mongodb://localhost:27017
DB_NAME=testdb
Output:
📄 All Users: [
name: 'Alice',
email: '[email protected]',
age: 25
✏️Updated: 1 document(s)
Deleted: 1 document(s)
🔌 Disconnected
Folder structure:
program11a
|------ .env
|------ manageDb.js
program11a/ .env:
MONGO_URI=mongodb://localhost:27017
program11a/manageDb.js:
require('dotenv').config();
const { MongoClient } = require('mongodb');
try {
await client.connect();
console.log('✅ Connected to MongoDB');
// 🔥 Drop Collection
const dropCollectionResult = await db.collection('students').drop();
console.log(' Collection dropped:', dropCollectionResult); // true
// 🔥 Drop Database
const dropDbResult = await db.dropDatabase();
console.log(' Database dropped:', dropDbResult); // true
} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('🔌 Disconnected from MongoDB');
}
}
main();
Output:
Folder structure:
mongo-queries
|------ .env
|------ queries.js
mongo-queries/ .env:
MONGO_URI=mongodb://localhost:27017
mongo-queries/ queries.js:
require('dotenv').config();
const { MongoClient } = require('mongodb');
try {
await client.connect();
console.log('✅ Connected to MongoDB');
const db = client.db('companyDB');
const employees = db.collection('employees');
// 🔁 Insert sample records
await employees.insertMany([
{ name: 'Alice', age: 25, dept: 'HR', salary: 3000 },
{ name: 'Bob', age: 30, dept: 'IT', salary: 5000 },
{ name: 'Carol', age: 28, dept: 'IT', salary: 4500 },
{ name: 'Dave', age: 35, dept: 'Finance', salary: 6000 },
{ name: 'Eve', age: 22, dept: 'HR', salary: 3200 }
]);
console.log('📥 Sample data inserted');
} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('\n🔌 Disconnected');
}
}
main();
Output:
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
{
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
{
_id: new ObjectId('6891df5603e52cad326b62ea'),
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
{
_id: new ObjectId('6891ae61c87819a49997af30'),
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Dave',
age: 35,
dept: 'Finance',
salary: 6000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Bob',
age: 30,
dept: 'IT',
salary: 5000
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Carol',
age: 28,
dept: 'IT',
salary: 4500
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Eve',
age: 22,
dept: 'HR',
salary: 3200
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
},
name: 'Alice',
age: 25,
dept: 'HR',
salary: 3000
🔌 Disconnected
Folder Structure:
todo-app/
├── views/
│ └── index.ejs
├── public/
│ └── styles.css
├── app.js
├── package.json
Install packages:
npm init -y
npm install express ejs body-parser uuid
todo-app/views/index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>To-Do List</h1>
<form action="/add" method="POST">
<input type="text" name="task" placeholder="New Task name" required>
<button type="submit">Add Task</button>
</form>
<ul>
<% tasks.forEach(task => { %>
<li>
<%= task.name %>
<a href="/complete/<%= task._id %>">Complete</a>
<form action="/complete/<%= task.id %>" method="POST";
style="display:inline;">
<button type="submit">
<% if (task.completed) { %> ☐
<% } else { %> ☐ <% } %>
</button>
</form>
todo-app/public/styles.css:
body {
font-family: Arial, sans-serif;
width: 50%;
margin: auto;
padding-top: 40px;
h1 {
text-align: center;
form {
margin-bottom: 20px;
ul {
list-style-type: none;
padding-left: 0;
li {
margin-bottom: 10px;
display: flex;
align-items: center;
}
button {
margin-right: 10px;
todo-app/app.js:
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');
// Routes
app.get('/', (req, res) => {
res.render('index', { tasks });
});
todo-app/package.json:
{
"name": "todo-app",
"version": "1.0.0",
"description": "A simple to-do list app using Node.js and Express.js",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [
"todo",
"nodejs",
"express"
],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"body-parser": "^1.20.3",
"ejs": "^3.1.10",
"express": "^4.21.2",
"uuid": "^9.0.1"
},
"type": "commonjs"
}
Output:
To-Do List
Add Task