0% found this document useful (0 votes)
87 views5 pages

Ex 4 Food Delivery APP

The document outlines the creation of a food delivery web application using Node.js and MongoDB. It details the project structure, installation of dependencies, front-end and back-end code, and instructions for setting up and running the application. The final result is a functional food order and delivery website where users can view restaurants and their menus.

Uploaded by

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

Ex 4 Food Delivery APP

The document outlines the creation of a food delivery web application using Node.js and MongoDB. It details the project structure, installation of dependencies, front-end and back-end code, and instructions for setting up and running the application. The final result is a functional food order and delivery website where users can view restaurants and their menus.

Uploaded by

hemnathsingh26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Ex: No: 4 FOOD ORDER AND DELIVERY APPLICATION

DATE :

AIM:
To create a food delivery website where users can order food from a particular restaurant
listed in the website.

PROCEDURE:
Prerequisite: Installation of Node.js and MongoDB

1. Set up your project structure:


Create a project folder and set up the following structure:
food-delivery-website/
➢ node_modules/
➢ public/
• index.html
• style.css
• script.js
➢ server.js
➢ package.json

2. Install required dependencies:


Open a terminal in your project directory and run:
✓ npm init -y
✓ npm install express
✓ npm install mongodb

3. Set up MongoDB:
Make sure MongoDB is installed and check it is running. (Use a cloud-based solution like
MongoDB Atlas.)

4. Front-End (public/index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script defer src="script.js"></script>
<title>Food Delivery</title>
</head>
<body>
<header>
<h1>Food Delivery</h1>
</header>
<main>
<section id="restaurant-list">
<!-- Restaurant listings will be added here dynamically -->
</section>
<section id="menu">
<!-- Menu items of selected restaurant will be added here dynamically -->
</section>
</main>
</body>
</html>
5. Front-End (public/style.css):
body, h1, h2, h3, p, ul, li {
margin: 0;
padding: 0;
}

body {
font-family: Arial, sans-serif;
}

header {
background-color: #333;
color: white;
text-align: center;
padding: 1rem;
}

main {
display: flex;
justify-content: space-between;
padding: 2rem;
}

#restaurant-list {
flex: 1;
padding-right: 2rem;
border-right: 1px solid #ddd;
}

.restaurant-card {
border: 1px solid #ddd;
padding: 1rem;
margin-bottom: 1rem;
cursor: pointer;
}

#menu {
flex: 2;
padding-left: 2rem;
}

.menu-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 0;
border-bottom: 1px solid #ddd;
}

.item-name {
font-weight: bold;
}

.item-price {
color: #555;
}
.add-to-cart-btn {
background-color: #007bff;
color: white;
border: none;
padding: 0.25rem 0.5rem;
cursor: pointer;
}
.add-to-cart-btn:hover {
background-color: #0056b3;
}

6. Front-End (public/script.js):
document.addEventListener('DOMContentLoaded', () => {
const restaurantList = document.getElementById("restaurant-list");
const menuSection = document.getElementById("menu");

// Replace this with actual data fetched from the server


const restaurantsData = [
{ name: "Restaurant 1", _id: "restaurant_id_1" },
{ name: "Restaurant 2", _id: "restaurant_id_2" },
];

// Function to populate the restaurant list


function populateRestaurantList() {
for (const restaurant of restaurantsData) {
const restaurantCard = document.createElement("div");
restaurantCard.classList.add("restaurant-card");
restaurantCard.textContent = restaurant.name;
restaurantCard.addEventListener("click", () => fetchMenu(restaurant._id));
restaurantList.appendChild(restaurantCard);
}
}

// Function to fetch and display the menu of a selected restaurant


function fetchMenu(restaurantId) {
// Replace this with AJAX request to the server to fetch menu data
const menuData = [
{ name: "Item A", price: 10.99 },
{ name: "Item B", price: 8.49 },
// ... more menu items
];

menuSection.innerHTML = '';

for (const item of menuData) {


const menuItem = document.createElement("div");
menuItem.classList.add("menu-item");
menuItem.innerHTML = `
<span class="item-name">${item.name}</span>
<span class="item-price">$${item.price.toFixed(2)}</span>
<button class="add-to-cart-btn">Add to Cart</button> `;
menuSection.appendChild(menuItem);
}
}

// Initialize the app


populateRestaurantList();
});
7. Back-End (server.js):
const express = require('express');
const app = express();
const port = 3000;
const MongoClient = require('mongodb').MongoClient;

const mongoURL = 'mongodb://localhost:27017';


const dbName = 'food_delivery_db';

app.use(express.static('public'));

MongoClient.connect(mongoURL, { useUnifiedTopology: true }, (err, client) => {


if (err) {
console.error('Error connecting to the database:', err);
return;
}

console.log('Connected to the database');


const db = client.db(dbName);

// API endpoint to fetch restaurant data


app.get('/restaurants', (req, res) => {
const restaurantsCollection = db.collection('restaurants');
restaurantsCollection.find({}).toArray((err, restaurants) => {
if (err) {
console.error('Error fetching restaurants:', err);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
res.json(restaurants);
});
});

// API endpoint to fetch menu items for a specific restaurant


app.get('/menu/:restaurantId', (req, res) => {
const restaurantId = req.params.restaurantId;
const menuCollection = db.collection('menu');
menuCollection.find({ restaurantId }).toArray((err, menuItems) => {
if (err) {
console.error('Error fetching menu items:', err);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
res.json(menuItems);
});
});

app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
});

8. Configure MongoDB:
Make sure your MongoDB server is running. Adjust the MongoDB connection URL (mongoURL)
and database name (dbName) in the server.js file as needed.
9. Run the Server:
In your terminal, navigate to your project directory and run:
✓ node server.js

This will start the server, and you should see the message "Server is listening at
http://localhost:3000".

10. Access the Website:


Open a web browser and navigate to http://localhost:3000 to see the food delivery website.

MongoDB shell Process:


In the MongoDB shell, you can create a new database using the use command. Replace
"food_delivery_db" with the name you want for your database:
✓ use food_delivery_db

Create Collections:
Collections are created automatically in MongoDB when you insert documents into them. We will
have two collections: restaurants and menu.

Insert Sample Data:


Insert sample data into the collections using the insertOne() and insertMany() methods.

For example, to insert sample data into the restaurants collection:


db.restaurants.insertMany([
{ name: "Restaurant 1", address: "123 Main St" },
{ name: "Restaurant 2", address: "324 New St" }
])

To insert sample data into the menu collection: (Replace "restaurant_id_1" and "restaurant_id_2"
with the actual _id values of the restaurants you inserted in the restaurants collection.)

db.menu.insertMany([
{ restaurantId: ObjectId("restaurant_id_1"), name: "Item A", price: 10.99 },
{ restaurantId: ObjectId("restaurant_id_1"), name: "Item B", price: 8.49 },
{ restaurantId: ObjectId("restaurant_id_2"), name: "Item C", price: 12.99 }
])

OUTPUT:

RESULT:
Thus, a simple food order and delivery web application was implemented and simulated
successfully using node.js and MongoDB.

You might also like