0% found this document useful (0 votes)
3 views35 pages

Full Stack Development Lab Manual

The document outlines a week-by-week guide for creating various Node.js applications, starting with a simple 'Hello World' app and progressing to a food delivery website. Each week includes steps for setting up the environment, writing code, and testing functionality, covering topics such as user authentication, file operations, and handling HTTP requests. The final project involves creating a food delivery system with restaurant listings and an order management feature.

Uploaded by

addagudi ashwini
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Full Stack Development Lab Manual

The document outlines a week-by-week guide for creating various Node.js applications, starting with a simple 'Hello World' app and progressing to a food delivery website. Each week includes steps for setting up the environment, writing code, and testing functionality, covering topics such as user authentication, file operations, and handling HTTP requests. The final project involves creating a food delivery system with restaurant listings and an order management feature.

Uploaded by

addagudi ashwini
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

WEEK-1: Create an application to setup node JS environment and display “Hello World”.

Step1: Open Visual Studio Code

Step 2: Create a folder called Hello-World and create a java script file ([Link]) in your folder

Filename: [Link]

// Code

[Link] (“Hello World”)

Output:

Hello World

WEEK 2: Create a Node JS application for user login system.

We'll create a simple user login system where a user can submit a username and password, and
the system will authenticate them based on predefined credentials.

Step 1: Create your project Folder:


Create a folder where you’ll put your [Link] application. Create a folder called Login-System

Step 2: Install necessary dependencies:

Initialize a [Link] Project: Inside your project folder, initialize a new [Link] project by
running:

PS E:\Login-System>npm init –y

-You'll need `express` for handling HTTP requests and `body-parser `for parsing request data.

PS E:\Login-System> npm install express body-parser

Step 3: Create the login system:

Create a java script file in your folder

File name: [Link]

//Code

const express = require('express');


const bodyParser = require('body-parser');

const app = express();

const port = 3005;

[Link]([Link]({ extended: true }));

// Predefined users (In real-world applications, this would come from a database)

const users = {

username: 'admin',

password: 'password123'

};

// Serve the login form

[Link]('/', (req, res) => {

[Link](`

<form method="POST" action="/login">

<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>

<button type="submit">Login</button>

</form>

`);

});

// Handle login POST request

[Link]('/login', (req, res) => {

const { username, password } = [Link];


if (username === [Link] && password === [Link]) {

[Link]('Login successful!');

} else {

[Link]('Invalid credentials');

});

[Link](port, () => {

[Link](`Server is running at [Link]

});

OUTPUT:

PS E:\FSD\Login-System>node [Link]

Server is running at [Link]

Open Your Browser: Open any browser (Google Chrome,Firefox,etc)

In the address bar, type [Link] and press Enter

You see the login form displayed in your browser. It will ask for a username and password.

Enter the username admin and the password password123 in the form. Click the login Button
If the credentials match, you will see the message Login successful!

If the credentials do not match, you will see the message Invalid credentials.
WEEK-3 Write a Node JS program to perform read, write and other operations on a file.

Filename: [Link]

const fs = require('fs');

// File path

const filePath = 'C:/Users/VAAGDEVI/Desktop/[Link]';

// 1. Write to a file

[Link]('Starting file write...');

[Link](filePath, 'Hello, [Link] file operations!', (err) => {

if (err) {

[Link]('Error writing to file:', err);

return;

[Link]('File written successfully.');

// 2. Read from the file

[Link]('Reading file...');

[Link](filePath, 'utf8', (err, data) => {

if (err) {

[Link]('Error reading from file:', err);

return;

[Link]('File content:', data);


//3. Append to the file

[Link]('Appending to file...');

[Link](filePath, '\nAppended text.', (err) => {

if (err) {

[Link]('Error appending to file:', err);

return;

[Link]('Text appended successfully.');

//4. Read the file again to see the changes

[Link]('Reading updated file...');

[Link](filePath, 'utf8', (err, data) => {

if (err) {

[Link]('Error reading from file:', err);

return;

[Link]('Updated file content:', data);

//5. Delete the file

[Link]('Deleting file...');

[Link](filePath, (err) => {

if (err) {

[Link]('Error deleting the file:', err);

return;
}

[Link]('File deleted successfully.');

});

});

});

});

});

Output:

PS C:\Users\VAAGDEVI\Desktop\FSD> node [Link]

Starting file write...

File written successfully.

Reading file...

File content: Hello, [Link] file operations!

Appending to file...

Text appended successfully.

Reading updated file...

Updated file content: Hello, [Link] file operations!

Appended text.

Deleting file...

File deleted successfully.


WEEK-4: Read Form Data from Query String and Generate Response in [Link]

PS C:\Users\VAAGDEVI\Desktop\FSD> npm init -y

Wrote to C:\Users\VAAGDEVI\Desktop\FSD\[Link]:

"name": "fsd",

"version": "1.0.0",

"main": "[Link]",

"scripts": {

"test": "echo \"Error: no test specified\"&& exit 1"

},

"keywords": [],

"author": "",

"license": "ISC",

"type": "commonjs",

"description": ""

PS C:\Users\VAAGDEVI\Desktop\FSD> npm install express body-parser

added 69 packages, and audited 70 packages in 2s

14 packages are looking for funding

run `npm fund` for details


found 0 vulnerabilities

File Name: [Link]

constexpress=require('express');

constapp=express();

constport=3008;

// Route to handle form data sent through query string

[Link]('/', (req, res) => {

[Link](`

<form method="GET" action="/greet">

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<button type="submit">Greet Me</button>

</form>

`);

});

// Route to process query string and generate response

[Link]('/greet', (req, res) => {

constname=[Link];

if (name) {

[Link](`Hello, ${name}! Welcome to the [Link] application.`);

} else {

[Link]('Please provide a name.');


}

});

[Link](port, () => {

[Link](`Server is running at [Link]

});

OUTPUT:

PS C:\Users\VAAGDEVI\Desktop\FSD>node [Link]

Server is running at [Link]


WEEK-5. Create a food delivery website where users can order food from a particular
restaurant listed in the website for handling http requests and responses using NodeJS.

To create a simple food delivery website using [Link] where users can order food from a
particular restaurant, you will need to follow these steps:

Step 1: Set up [Link] Project

Create a new project directory:

mkdir food-delivery-app

cd food-delivery-app

Step 2: Initialize a new [Link] project:

npm init -y

Step 3: Install required dependencies: You'll need the Express framework to handle HTTP
requests and responses.

npm install express body-parser

Step 4: Create the main server file: Create a file called [Link] in the project directory
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = [Link] || 3000;
// Middleware
[Link](cors());
[Link]([Link]());
[Link]([Link]('public'));
[Link]([Link]());

// Sample restaurant data


const restaurants = [
{
id: 1,
name: "Tasty Bites",
cuisine: "Italian",
rating: 4.5,
deliveryTime: "30-40 min",
image: "/images/[Link]",
menu: [
{
id: 1,
name: "Margherita Pizza",
price: 399,
description: "Fresh tomatoes, mozzarella, basil, and olive oil",
image: "/images/[Link]"
},
{
id: 2,
name: "Pasta Carbonara",
price: 349,
description: "Creamy sauce with pancetta and parmesan",
image: "/images/[Link]"
},
{
id: 3,
name: "Tiramisu",
price: 249,
description: "Classic Italian dessert with coffee and mascarpone",
image: "/images/[Link]"
}
]
},
{
id: 2,
name: "Spice Garden",
cuisine: "Indian",
rating: 4.3,
deliveryTime: "35-45 min",
image: "/images/[Link]",
menu: [
{
id: 4,
name: "Butter Chicken",
price: 449,
description: "Creamy tomato curry with tender chicken",
image: "/images/[Link]"
},
{
id: 5,
name: "Vegetable Biryani",
price: 299,
description: "Aromatic rice with mixed vegetables and spices",
image: "/images/[Link]"
},
{
id: 6,
name: "Garlic Naan",
price: 69,
description: "Freshly baked bread with garlic and butter",
image: "/images/[Link]"
}
]
},
{
id: 3,
name: "Sushi Master",
cuisine: "Japanese",
rating: 4.7,
deliveryTime: "25-35 min",
image: "/images/[Link]",
menu: [
{
id: 7,
name: "California Roll",
price: 449,
description: "Crab, avocado, and cucumber roll",
image: "/images/[Link]"
},
{
id: 8,
name: "Salmon Nigiri",
price: 499,
description: "Fresh salmon over pressed sushi rice",
image: "/images/[Link]"
},
{
id: 9,
name: "Tempura Udon",
price: 399,
description: "Thick noodles in hot broth with tempura",
image: "/images/[Link]"
}
]
}
];

// Routes
[Link]('/api/restaurants', (req, res) => {
[Link](restaurants);
});

[Link]('/api/restaurants/:id', (req, res) => {


const restaurant = [Link](r => [Link] === parseInt([Link]));
if (!restaurant) return [Link](404).json({ message: 'Restaurant not found' });
[Link](restaurant);
});

// Order endpoint (mocked, no DB)


[Link]('/api/orders', (req, res) => {
const { items, totalAmount, customerDetails } = [Link];

if (!items || [Link] === 0) {


return [Link](400).json({ error: 'No items in order' });
}

// Mock order confirmation


const order = {
id: [Link](), // Mock ID
items,
totalAmount,
customerDetails,
status: 'pending'
};

[Link]('Received order:', order);


[Link](201).json({ message: 'Order placed successfully!', order });
});

[Link]('/', (req, res) => {


[Link]([Link](__dirname, 'public', '[Link]'));
});

[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
Step 5: Create the main orders file: Create a file called [Link] in the project directory
// Mock order storage (in-memory array)
const orders = [];

function createOrder(data) {
const { restaurantId, items, totalAmount, customerDetails } = data;

const newOrder = {
id: [Link](), // mock unique ID
restaurantId,
items: [Link](item => ({
foodItemId: [Link],
quantity: [Link] || 1,
price: [Link]
})),
totalAmount,
customerDetails,
status: 'pending',
orderDate: new Date()
};

[Link](newOrder);
return newOrder;
}

function getAllOrders() {
return orders;
}

[Link] = {
createOrder,
getAllOrders
};

Step 6: Create a folder name public in that create file name [Link] and create folder name
images in public
let cart = [];
let restaurants = [];

function formatPrice(price) {
[Link]('Formatting price:', price);
const formatted = `₹${[Link](0)}`;
[Link]('Formatted price:', formatted);
return formatted;
}

// Fetch restaurants when the page loads


[Link]('DOMContentLoaded', async () => {
try {
const response = await fetch('/api/restaurants');
restaurants = await [Link]();
[Link]('Fetched restaurants:', restaurants);
displayRestaurants();
} catch (error) {
[Link]('Error fetching restaurants:', error);
}
});

function displayRestaurants() {
const restaurantsList = [Link]('restaurants-list');
[Link] = [Link](restaurant => `
<div class="restaurant-card">
<div class="restaurant-image">
<img src="${[Link]}" alt="${[Link]}">
</div>
<div class="restaurant-info">
<h2>${[Link]}</h2>
<p class="cuisine">${[Link]}</p>
<div class="restaurant-meta">
<span class="rating">⭐ ${[Link]}</span>
<span class="delivery-time">🕒 ${[Link]}</span>
</div>
</div>
<div class="menu">
<h3>Menu</h3>
${[Link](item => `
<div class="menu-item">
<div class="menu-item-image">
<img src="${[Link]}" alt="${[Link]}">
</div>
<div class="menu-item-info">
<h4>${[Link]}</h4>
<p class="description">${[Link]}</p>
<div class="price-action">
<span class="price">${formatPrice([Link])}</span>
<button onclick="addToCart(${[Link]}, ${[Link]})">Add to Cart</button>
</div>
</div>
</div>
`).join('')}
</div>
</div>
`).join('');
}

function addToCart(restaurantId, itemId) {


const restaurant = [Link](r => [Link] === restaurantId);
const item = [Link](i => [Link] === itemId);

[Link]({
...item,
restaurantId
});

updateCart();
}

function updateCart() {
const cartItems = [Link]('cart-items');
const cartCount = [Link]('cart-count');
const cartTotal = [Link]('cart-total');

[Link] = [Link];

[Link] = [Link]((item, index) => `


<div class="cart-item">
<div class="cart-item-image">
<img src="${[Link]}" alt="${[Link]}">
</div>
<div class="cart-item-info">
<h4>${[Link]}</h4>
<p class="description">${[Link]}</p>
<div class="price-action">
<span class="price">${formatPrice([Link])}</span>
<button onclick="removeFromCart(${index})">Remove</button>
</div>
</div>
</div>
`).join('');

const total = [Link]((sum, item) => sum + [Link], 0);


[Link] = formatPrice(total);
}

function removeFromCart(index) {
[Link](index, 1);
updateCart();
}

function toggleCart() {
const cartSidebar = [Link]('cart-sidebar');
[Link]('active');
}

function checkout() {
if ([Link] === 0) {
alert('Your cart is empty!');
return;
}

const modal = [Link]('checkout-modal');


[Link] = 'block';
}

[Link]('checkout-form').addEventListener('submit', async (e) => {


[Link]();
const formData = new FormData([Link]);
const customerDetails = {
name: [Link]('name'),
email: [Link]('email'),
address: [Link]('address'),
phone: [Link]('phone')
};
[Link]('Customer Details:', customerDetails);

try {
const response = await fetch('/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({
items: cart,
totalAmount: [Link]((sum, item) => sum + [Link], 0),
customerDetails
})
});

if (![Link]) {
const errorText = await [Link](); // Grab the error text (might be HTML)
throw new Error(`Server error: ${errorText}`);
}
const result = await [Link]();

if ([Link]) {
alert('Order placed successfully!');
cart = [];
updateCart();
[Link]('checkout-modal').[Link] = 'none';
[Link]('checkout-form').reset();
} else {
throw new Error([Link]);
}
} catch (error) {
alert('Error placing order: ' + [Link]);
}
});

Step 7: create a file names [Link] and [Link] in the public folder

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Food Delivery App</title>
<link rel="stylesheet" href="[Link]">
<link href="[Link] rel="stylesheet">
</head>
<body>
<header>
<nav>
<div class="logo">FoodExpress</div>
<div class="cart-icon" onclick="toggleCart()">
🛒 <span id="cart-count">0</span>
</div>
</nav>
</header>

<main>
<section class="restaurants-container">
<h1>Our Restaurants</h1>
<div id="restaurants-list"></div>
</section>

<div id="cart-sidebar" class="cart-sidebar">


<h2>Your Cart</h2>
<div id="cart-items"></div>
<div class="cart-total">
<p>Total: ₹<span id="cart-total">0</span></p>
<button onclick="checkout()" class="checkout-btn">Checkout</button>
</div>
</div>
</main>

<div id="checkout-modal" class="modal">


<div class="modal-content">
<h2>Checkout</h2>
<form id="checkout-form">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<input type="text" name="address" placeholder="Address" required>
<input type="tel" name="phone" placeholder="Phone" required>
<button type="submit" class="checkout-btn">Place Order</button>
</form>
</div>
</div>

<script src="[Link]?v=2"></script>
</body>
</html>

[Link]
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}

body {
background-color: #f5f5f5;
}

header {
background-color: #ffffff;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
padding: 1rem 2rem;
}

nav {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 1200px;
margin: 0 auto;
}

.logo {
font-size: 1.5rem;
font-weight: 600;
color: #ff4757;
}

.cart-icon {
cursor: pointer;
font-size: 1.2rem;
}

main {
max-width: 1200px;
margin: 2rem auto;
padding: 0 1rem;
}

.restaurants-container h1 {
margin-bottom: 2rem;
color: #2d3436;
}

#restaurants-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
}

.restaurant-card {
background: white;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
overflow: hidden;
}

.restaurant-image {
margin: -1rem -1rem 1rem -1rem;
height: 200px;
overflow: hidden;
}

.restaurant-image img {
width: 100%;
height: 100%;
object-fit: cover;
}

.restaurant-info {
margin-bottom: 1.5rem;
}

.restaurant-meta {
display: flex;
gap: 1rem;
margin-top: 0.5rem;
color: #666;
}

.cuisine {
color: #666;
font-style: italic;
}

.rating {
color: #ffa41c;
}

.menu {
margin-top: 1.5rem;
}

.menu h3 {
margin-bottom: 1rem;
color: #2d3436;
}

.menu-item {
display: grid;
grid-template-columns: 100px 1fr;
gap: 1rem;
padding: 1rem 0;
border-bottom: 1px solid #eee;
}

.menu-item-image {
width: 100px;
height: 100px;
border-radius: 8px;
overflow: hidden;
}

.menu-item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}

.menu-item-info h4 {
margin-bottom: 0.5rem;
color: #2d3436;
}

.description {
color: #666;
font-size: 0.9rem;
margin-bottom: 0.5rem;
}

.price-action {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.5rem;
}

.price {
font-weight: 600;
color: #2d3436;
}

button {
background: #ff4757;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s ease;
}

button:hover {
background: #ff6b81;
}

.cart-sidebar {
position: fixed;
right: -400px;
top: 0;
width: 400px;
height: 100vh;
background: white;
box-shadow: -2px 0 5px rgba(0,0,0,0.1);
padding: 2rem;
transition: right 0.3s ease;
}

.[Link] {
right: 0;
}

.cart-total {
position: absolute;
bottom: 2rem;
left: 2rem;
right: 2rem;
}

.cart-item {
display: grid;
grid-template-columns: 80px 1fr;
gap: 1rem;
padding: 1rem 0;
border-bottom: 1px solid #eee;
}

.cart-item-image {
width: 80px;
height: 80px;
border-radius: 8px;
overflow: hidden;
}

.cart-item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}

.cart-item-info h4 {
margin-bottom: 0.25rem;
color: #2d3436;
}

.checkout-btn {
width: 100%;
padding: 1rem;
background: #ff4757;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 1rem;
}

.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
}

.modal-content {
background: white;
padding: 2rem;
border-radius: 10px;
width: 90%;
max-width: 500px;
margin: 2rem auto;
}

#checkout-form {
display: flex;
flex-direction: column;
gap: 1rem;
}

#checkout-form input {
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 5px;
}

@media (max-width: 768px) {


.cart-sidebar {
width: 100%;
right: -100%;
}
}

Open Terminal

C:\Users\VAAGDEVI\Downloads\food-delivery-app> node [Link]

Server is running on port 3000

Open Browser and Type [Link]

WEEK-6: Implement a program with basic commands on databases and collections using
MongoDB.

To implement a program with basic commands on databases and collections using MongoDB,
you will need to install MongoDB, set up a MongoDB instance, and use the MongoDB [Link]
driver to interact with the database.

Step 1: Install MongoDB and the MongoDB [Link] Driver


Mongodb installation

1. Download the MongoDB Installer:


 Go to the MongoDB Download Center.
 You can also install directly by following this link
[Link]
 Select the "Windows" platform and choose the "msi" package.
 Download the latest version of MongoDB Community Edition.

2. Run the Installer:


 Locate the downloaded .msi file.
 Double-click the file to start the installation wizard.
 Follow the on-screen instructions, including choosing a setup type (e.g., "Complete").
 Click the Install button to start the MongoDB installation process:
 After clicking on the install button installation of MongoDb begins:

Step 4: Complete Installation

 Now click the Finish button to complete the MongoDB installation process:

Step 5: Set Environment Variables

 Now we go to the location where MongoDB installed and copy the path
 Now, to create an environment variable open system properties >> Environment
Variable >> System variable >> path >> Edit Environment variable
 paste the copied link to your environment system and click Ok:

Run MongoDB Server (mongod)

Step 1. Start MongoDB Service

 After setting the environment variable, we will run the MongoDB server, i.e. mongod.

 So, open the command prompt and run the following command:

mongod

When you run this command you will get an error i.e. C:/data/db/ not found.

Step 2. Create Required Folders

 Now, Open C drive and create a folder named “data”

 Inside the data folder create another folder named “db“.

Step 3. Restart MongoDB


 After creating these folders. Again open the command prompt and run the following
command:

mongod

 Now, this time the MongoDB server (i.e., mongod) will run successfully.
 If you’re getting any error enter to the location where the mongodb is located i.e
The path that you have given in Environment variables
 Run the above command again i.e mongod

Run the MongoDB Shell (mongosh)

Step 1. Connect to MongoDB Server with mongosh

 Now we are going to connect our server (mongod) with the mongo shell. So, keep that
mongod window

 open a new command prompt window and type:

mongosh

 You are now connected to the MongoDB shell.

Please do not close the mongod window if you close this window your server will stop working
and it will not able to connect with the mongo shell.

Step 2. Create a Database


Now we can make a new database, collections, and documents in our shell. Use the following
command within the mongosh shell to create a new database:

use database_name

The use Database_name command makes a new database in the system if it does not exist, if the
database exists it uses that database:

use fsd

Step 3: Add Data to a Collection

Insert a document into a collection using:

db.collection_name.insertOne({field: value})

The db.Collection_name command makes a new collection in the fsd database and
the insertOne() method inserts the document in the student collection:

[Link]({shivani:100})

Create and handle database in MongoDB using various commands.

1) Displaying all the databases present in the system

testDB>show dbs
2) Drop Database

use testDB

testDB>[Link]()

collection:-

We can perform various operations such as insert,delete and update on the collection

1) Create collection:-

We can create collection explicitly using createcollection command

test>use mystudent

mystudent>[Link]("student_details")

2) Display collection:-

mystudent> show collections

show student_details

mystudent>

3) Drop collection:-

mystudent>db.student_details.drop()

mystudent>

4) insert documents with in the collection:-

> [Link]("empDetails")

> [Link](

First_Name: "Radhika",

Last_Name: "Sharma",

Date_Of_Birth: "1995-09-26",

e_mail: "radhika_sharma.123@[Link]",
phone: "9000012345"

},

First_Name: "Rachel",

Last_Name: "Christopher",

Date_Of_Birth: "1990-02-16",

e_mail: "Rachel_Christopher.123@[Link]",

phone: "9000054321"

},

First_Name: "Fathima",

Last_Name: "Sheik",

Date_Of_Birth: "1990-02-16",

e_mail: "Fathima_Sheik.123@[Link]",

phone: "9000054321"

5) delete documents:-

[Link]({First_Name: "Fathima"})

6) update Documents:-

student_details=[{"name":"xyz","age":35},

{"name":"abc","age":60}]

db.student_details.updateOne( { name: "xyz" }, { $set: { age:0 } } )

Week-7 Implement CRUD operations on the given dataset using MongoDB.


mongodb-crud-project/

├── data/

│ └── [Link]

├── src/

│ └── [Link]

│ └── [Link]

└── [Link]

 [Link] - Sample dataset.


 [Link] - Handles MongoDB connection.
 [Link] - Implements CRUD operations.
Step 1: Create the Project Folder

mkdir mongodb-crud-project

cd mongodb-crud-project

Step 2: Initialize [Link] Project

npm init -y

Step 3: Install MongoDB Driver

npm install mongodb

Step 4: Setting Up MongoDB Connection ([Link])

const { MongoClient } = require('mongodb');

//imports the MongoClient class from the mongodb package.

// Replace with your MongoDB URI

const uri = 'mongodb://[Link]:27017';

//The uri specifies the MongoDB connection string.


const client = new MongoClient(uri);

//new MongoClient(uri) creates a new instance of the MongoClient class.

//The client object will be used to connect to and interact with the MongoDB server.

async function connectDB() {

try {

await [Link]();
//This tells the client to connect to the MongoDB [Link] this is an asynchronous operation,
await ensures it completes before moving to the next step.
[Link]('Connected to MongoDB');
const db = [Link]('crudDB');

//Selects (or creates if it doesn't exist) a database named "crudDB".

return db;

} catch (error) {

[Link]('Connection error:', error);

[Link] = connectDB;

Step 5: Implementing CRUD Operations ([Link])

const connectDB = require('./db');

// Create

async function createDocument(collectionName, document) {

const db = await connectDB();

const collection = [Link](collectionName);


const result = await [Link](document);

[Link]('Document inserted:', [Link]);

// Read

async function readDocuments(collectionName, query = {}) {

const db = await connectDB();

const collection = [Link](collectionName);

const documents = await [Link](query).toArray();

[Link]('Documents found:', documents);

return documents;

// Update

async function updateDocument(collectionName, filter, updateDoc) {

const db = await connectDB();

const collection = [Link](collectionName);

const result = await [Link](filter, { $set: updateDoc });

[Link]('Document updated:', [Link]);

// Delete

async function deleteDocument(collectionName, filter) {

const db = await connectDB();

const collection = [Link](collectionName);


const result = await [Link](filter);

[Link]('Document deleted:', [Link]);

// Export functions

[Link] = {

createDocument,

readDocuments,

updateDocument,

deleteDocument

};

Step 6: Running the Operations

(mongodb-crud-project/ [Link])

const crud = require('./src/crudOperations');

async function runCRUD() {

await [Link]('users', { name: 'John Doe', age: 30 });

await [Link]('users');

await [Link]('users', { name: 'John Doe' }, { age: 31 });

await [Link]('users', { name: 'John Doe' });

runCRUD();

Step 7: Run the Project

node [Link]
Output:-

Connected to MongoDB

Document inserted: new ObjectId('67eaf37531fe49d7cdb9b78f')

Connected to MongoDB

Documents found: [

_id: new ObjectId('67eaf37531fe49d7cdb9b78f'),

name: 'John Doe',

age: 30

Connected to MongoDB

Document updated: 1

Connected to MongoDB

Document deleted: 1

You might also like