0% found this document useful (0 votes)
14 views

Final Term CS Solution

The document covers key concepts in web development, including event propagation (capturing vs. bubbling), the MVC design pattern, advantages of async/await over promises, and improving MongoDB query performance. It also provides code examples for setting up an Express server, creating a Mongoose schema and model, and building a React feedback form. Overall, it serves as a concise guide for implementing various web application functionalities.

Uploaded by

Muhammad Yaseen
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)
14 views

Final Term CS Solution

The document covers key concepts in web development, including event propagation (capturing vs. bubbling), the MVC design pattern, advantages of async/await over promises, and improving MongoDB query performance. It also provides code examples for setting up an Express server, creating a Mongoose schema and model, and building a React feedback form. Overall, it serves as a concise guide for implementing various web application functionalities.

Uploaded by

Muhammad Yaseen
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/ 4

Q2: SHORT QUESTIONS

a. Capturing vs. Bubbling in Event Propagation

Event Phase Description Order


Capturing (Trickling Event moves from the topmost ancestor (document) Top →
Down) to the target element. Target
Bubbling (Propagating Event moves from the target element up to the Target →
Up) document. Top

Example:

document.getElementById("child").addEventListener("click", () => alert("Child


clicked!"), true); // Capturing
document.getElementById("child").addEventListener("click", () => alert("Child
clicked!"), false); // Bubbling

b. MVC Design Pattern

MVC (Model-View-Controller) is a software design pattern for developing web applications:

1. Model: Manages data and business logic.


2. View: Displays data and handles UI.
3. Controller: Acts as a bridge between Model and View, handling user inputs.

c. Advantages of async/await Over Promises

1. Synchronous-like Code: Easier to read and write.


2. Better Error Handling: Uses try-catch instead of .catch().
3. Avoids Nested .then() Calls: Prevents promise chaining.
4. More Readable for Complex Asynchronous Code.

Example:

async function fetchData() {


try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}

d. Improving MongoDB Query Performance (Especially Sorting)

1. Indexing: Use indexes on frequently queried fields.


2. Use Projection: Retrieve only required fields (.find({}, { name: 1, _id: 0 })).
3. Limit and Skip: Use .limit() and .skip() to avoid large dataset scans.
4. Avoid Regex Searches: Use full-text search instead.
5. Use Aggregation Pipelines: Optimize queries with $match, $sort, and $limit.

e. Express Server Listening on Port 6000

const express = require('express');


const app = express();

app.get('/', (req, res) => {


res.send('WP Final Exam');
});

app.listen(6000, () => {
console.log('Server is running on port 6000');
});

Q3: MongoDB

a. Mongoose Schema for Reservations Collection

const mongoose = require('mongoose');

const reservationSchema = new mongoose.Schema({


customerName: String,
date: Date,
time: String,
tableNumber: Number,
guests: Number
});

module.exports = mongoose.model('Reservation', reservationSchema);

b. Creating a Mongoose Model

const Reservation = mongoose.model('Reservation', reservationSchema);

c. Function to Find Reservations on a Specific Date

javascript
CopyEdit
async function findReservationsOnDate(date) {
const reservations = await Reservation.find({ date: new Date(date) });
console.log(reservations);
}

Q4: EXPRESS JS & REACT JS

Task 1: Express.js Backend


const express = require('express');
const cors = require('cors');
const app = express();

app.use(express.json());
app.use(cors());

let feedbacks = []; // In-memory storage

app.post('/api/feedback', (req, res) => {


const { rating, comment } = req.body;
if (!rating || !comment) {
return res.status(400).json({ message: "Rating and comment are
required" });
}
feedbacks.push({ rating, comment });
res.json({ message: "Feedback submitted successfully" });
});

app.listen(5000, () => {
console.log("Server running on port 5000");
});

Task 2: React.js Frontend

import React, { useState } from 'react';

export default function FeedbackForm() {


const [rating, setRating] = useState('');
const [comment, setComment] = useState('');
const [message, setMessage] = useState('');

const handleSubmit = async (e) => {


e.preventDefault();
const response = await fetch('http://localhost:5000/api/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ rating, comment })
});
const data = await response.json();
setMessage(data.message);
};

return (
<div>
<h2>Submit Feedback</h2>
<form onSubmit={handleSubmit}>
<input type="number" placeholder="Rating (1-5)"
value={rating} onChange={e => setRating(e.target.value)} required />
<textarea placeholder="Comment" value={comment} onChange={e
=> setComment(e.target.value)} required></textarea>
<button type="submit">Submit</button>
</form>
{message && <p>{message}</p>}
</div>
);
}

You might also like