0% found this document useful (0 votes)
115 views40 pages

MongoDB Schema Design for E-Commerce

The document provides an overview of web development and the MEAN stack, including definitions, roles, and comparisons between front-end and back-end development. It covers key components of the MEAN stack (MongoDB, Express.js, Angular, Node.js), advantages and limitations, as well as CRUD operations in MongoDB. Additionally, it discusses the architecture of the MEAN stack and the differences between MEAN and MERN stacks.
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)
115 views40 pages

MongoDB Schema Design for E-Commerce

The document provides an overview of web development and the MEAN stack, including definitions, roles, and comparisons between front-end and back-end development. It covers key components of the MEAN stack (MongoDB, Express.js, Angular, Node.js), advantages and limitations, as well as CRUD operations in MongoDB. Additionally, it discusses the architecture of the MEAN stack and the differences between MEAN and MERN stacks.
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

MEA(R)N IMPORTANT QUESTION FOR END SEM

Unit 1: Web Development & MEAN Stack Basics


Short Answer (2-5 Marks)

1. What is web development?

Ans. Web development is the process of creating websites and web applications. It includes
designing, coding, and maintaining web pages using different technologies. It is broadly
categorized into:

• Front-end development (UI/UX design, responsiveness)


• Back-end development (server-side logic, database management)
• Full-stack development (both front-end and back-end combined)

2. What is the role of a client in web development?

Ans. The client is the user's device (such as a computer, tablet, or smartphone) that interacts with
a website via a web browser. The browser requests data from the server and displays it for the
user. The client-side typically includes:

• HTML, CSS, and JavaScript for rendering web pages.


• Front-end frameworks like React or Angular for interactive interfaces.

3. Differentiate between front-end and back-end development.

Ans.

• Front-end Development (Client-side):

• Focuses on the visual and interactive aspects of a website.


• Uses HTML, CSS, JavaScript, and frameworks like React, Angular, Vue.js.
• Handles user interface (UI) and experience (UX).

• Back-end Development (Server-side):

• Manages the database, server logic, and APIs.


• Uses programming languages like Node.js, Python, Java, PHP.
• Ensures proper authentication, security, and data handling.

4. What does MEAN stand for in the MEAN stack? (MCQ included)

Ans.
MongoDB, Express.js, Angular, Node.js

• MongoDB → NoSQL database for storing data.

• Express.js → Web framework for Node.js to handle backend requests.

• Angular → Front-end framework for building interactive UIs.

• Node.js → JavaScript runtime for executing server-side code.

5. What are the main components of the MEAN stack?

Ans.

The MEAN stack consists of:

• MongoDB: A NoSQL database for storing data in JSON format.


• Express.js: A lightweight web framework for handling server-side logic.
• Angular: A front-end framework for creating dynamic web applications.
• Node.js: A runtime environment that allows JavaScript to run on the server.

6. Why is JavaScript important in web development?

Ans.

JavaScript is a core technology for web development because:

• It makes web pages interactive and dynamic.


• It works on both client-side (browser) and server-side (Node.js).
• It supports modern frameworks like React, Angular, Vue.
• It allows real-time communication (e.g., chat applications).

7. List three popular web development frameworks and their uses.

Ans.

• React.js (Front-end) → Used for building single-page applications (SPAs) and dynamic user
interfaces.

• Express.js (Back-end) → A lightweight framework for handling HTTP requests, APIs, and
middleware in Node.js.

• Django (Back-end) → A Python-based framework used for scalable and secure web
applications.

8. What is JSON, and why is it used in the MEAN stack?


Ans.

• JSON (JavaScript Object Notation) is a lightweight data format used for storing and
exchanging data.

• It is widely used in the MEAN stack because:

• MongoDB stores data in JSON-like format (BSON).


• Angular uses JSON to send and receive data from APIs.
• Node.js and Express.js process data in JSON format.

9. What is the correct syntax for linking an external CSS file in HTML? *(MCQ included)*

Ans.

• <link rel="stylesheet" href="styles.css">

• This tag is placed inside the <head> section of an HTML document to apply styles from an
external CSS file.

10. What is the difference between SQL and NoSQL databases?

• SQL Databases (Relational Databases):

• Uses structured tables with predefined schemas.


• Examples: MySQL, PostgreSQL, SQL Server.
• Best for structured data with relationships.

• NoSQL Databases (Non-relational Databases):

• Stores unstructured or semi-structured data.


• Examples: MongoDB, Firebase, CouchDB.
• Best for big data and applications with flexible schemas.

Long Answer (7-10 Marks)

11. Explain full-stack development with examples.

Ans.

Full-stack development refers to the ability to develop both the front-end (client-side) and back-end
(server-side) of a web application. A full-stack developer is proficient in designing user interfaces,
managing databases, handling server-side logic, and integrating APIs.
Components of Full-Stack Development

1. Front-end (Client-side) Development:


o Deals with user interface (UI) and experience (UX).
o Technologies: HTML, CSS, JavaScript, React.js, Angular, Vue.js.
o Example: A shopping website where users can browse products, add items to a cart, and
check out.
2. Back-end (Server-side) Development:
o Handles business logic, authentication, and database interactions.
o Technologies: Node.js, Python (Django/Flask), Java (Spring Boot), PHP (Laravel).
o Example: A server that processes user logins, manages product details, and updates
inventory.
3. Database Management:
o Stores and retrieves data efficiently.
o Technologies: SQL (MySQL, PostgreSQL) and NoSQL (MongoDB, Firebase).
o Example: A database storing user profiles, purchase history, and product details.
4. Version Control & Deployment:
o Tools: Git, GitHub, Docker, CI/CD, AWS, Heroku.
o Helps in code collaboration, deployment, and hosting.

Example of a Full-Stack Web Application

E-commerce Platform (Amazon-like website)

• Front-end: Users browse products, filter results, and add items to the cart using React.js.
• Back-end: The server processes user requests, checks inventory, and confirms orders using
Node.js and Express.js.
• Database: MongoDB stores user profiles, order history, and product listings

12. Describe the MEAN stack architecture with a diagram.

Ans.

The MEAN stack is a JavaScript-based technology stack for full-stack web development. It consists of:

• MongoDB – NoSQL database for storing data in JSON format.


• Express.js – Back-end framework for handling requests and APIs.
• Angular – Front-end framework for building dynamic user interfaces.
• Node.js – JavaScript runtime environment for server-side logic.

MEAN Stack Architecture

The MEAN stack follows a three-tier architecture:


1. Client-side (Angular): The browser loads the Angular framework, which makes API requests to
the back-end.
2. Server-side (Node.js + Express.js): The server receives API requests, processes business logic,
and interacts with the database.
3. Database (MongoDB): Stores application data in a NoSQL format and responds to queries from
the back-end.

Diagram of MEAN Stack Architecture

• Step 1: The user interacts with the Angular front-end interface.

• Step 2: Angular sends HTTP requests to the Express.js server via API calls.

• Step 3: Node.js processes the request and interacts with the MongoDB database.

• Step 4: MongoDB retrieves or updates data and sends the response back to the server.

• Step 5: The server sends the processed data back to Angular for display.

13. Compare MEAN Stack and MERN Stack.

Ans.
Conclusion:

• MEAN stack is suitable for enterprise-grade applications with strong structure and
maintainability.
• MERN stack is ideal for modern web applications that require flexibility and component-based
development.

14. Discuss advantages & limitations of using the MEAN stack.

Ans.

Advantages of the MEAN Stack

1. Full JavaScript Stack:


o Uses JavaScript across front-end and back-end, making development smoother.
2. NoSQL Database (MongoDB):
o Stores data in JSON format, making it easy to work with APIs.
3. Scalability:
o Suitable for large-scale applications that need high performance.
4. MVC Architecture:
o Angular follows the Model-View-Controller (MVC) pattern for better code organization.
5. Efficient Performance:
o Node.js is event-driven and non-blocking, improving app speed.
6. Rich Ecosystem:
o Huge community support and available libraries (NPM modules).
Limitations of the MEAN Stack

1. Steep Learning Curve:


o Angular is complex and requires knowledge of TypeScript.
2. NoSQL Limitations:
o MongoDB lacks strong relational capabilities, making it harder to handle complex
relationships.
3. Security Concerns:
o Node.js applications are vulnerable to injections, cross-site scripting (XSS), and CSRF
attacks if not properly secured.
4. Server-side Rendering (SSR) Issues:
o Angular-based applications might face SEO challenges since they rely on client-side
rendering.
5. Scalability Challenges for Heavy Computation:
o Node.js is single-threaded, which can cause performance bottlenecks for CPU-intensive
tasks.

Final Thoughts

• MEAN Stack is a powerful and modern solution for full-stack JavaScript development.
• It is best for scalable, single-page applications, real-time applications, and cloud-based
solutions.
• However, developers need to address security and performance optimization to use it
effectively.

---

Unit 2: MongoDB (Database Layer)


Short Answer (2-5 Marks)

15. What is MongoDB, and how is it different from relational databases?

Ans.

MongoDB is a NoSQL database that stores data in a document-oriented format using JSON-
like BSON documents. Unlike relational databases (SQL-based), MongoDB:

• Stores data as documents instead of rows and tables.


• Uses a flexible schema rather than predefined table structures.
• Scales horizontally using sharding, whereas relational databases scale vertically.
16. Define collections and documents in MongoDB.

Ans.

• Collection: A group of related documents (similar to tables in SQL).

• Document: A single record in MongoDB, stored as a JSON-like BSON object.


Example:

{ "_id": 1, "name": "John Doe", "age": 25, "city": "New York" }

17. What is a NoSQL database, and why is MongoDB categorized as NoSQL?

Ans.

A NoSQL database is a non-relational database designed to handle large-scale, unstructured,


or semi-structured data. MongoDB is categorized as NoSQL because:

• It stores data in JSON-like documents instead of tables.


• It supports dynamic schemas, making it flexible.
• It is designed for horizontal scaling across distributed systems.

18. What are some advantages of using MongoDB for web development?

Ans.

1. Flexible Schema – No need for predefined structures.


2. Scalability – Supports horizontal scaling.
3. High Performance – Fast read/write operations.
4. JSON-like Data Model – Easy integration with web applications.
5. Indexing – Improves query performance.

19. Which method is used to insert a single document into a MongoDB collection? (MCQ
included)

Ans.

The insertOne() method is used to insert a single document.

Example:

db.users.insertOne({ "name": "Alice", "age": 30, "city": "Paris" });

20. What is CRUD, and explain the Create operation in MongoDB.

Ans.
• CRUD stands for Create, Read, Update, and Delete – the four basic operations on a database.

• Create Operation in MongoDB:

• The insertOne() method is used to insert a single document.


• The insertMany() method is used to insert multiple documents.

Example:

db.products.insertOne({ "name": "Laptop", "price": 50000, "brand": "HP" });

21. What is indexing in MongoDB, and why is it useful?

Ans. Indexing in MongoDB improves query performance by allowing faster retrieval of


documents. Without indexes, MongoDB performs a full collection scan, which is slow.
Example of creating an index:

db.users.createIndex({ "name": 1 });

Here, 1 represents ascending order sorting.

22. Write a MongoDB query to retrieve all documents from a collection.

Ans.

To retrieve all documents from a collection, use the find() method:

db.users.find({});

This will return all documents in the users collection.

23. How do you perform pagination in MongoDB?

Ans.

Pagination in MongoDB is done using limit() and skip():

db.users.find().skip(10).limit(5);

This retrieves 5 documents, skipping the first 10.

Long Answer (8-10 Marks)

24. Explain the CRUD operations in MongoDB with examples.


Ans.

CRUD stands for Create, Read, Update, and Delete, the four fundamental operations performed on a
database.

1. Create Operation (C)

• MongoDB provides the insertOne() method to insert a single document and insertMany()
to insert multiple documents.
• Example:

// Insert a single document

db.students.insertOne({ "name": "Alice", "age": 22, "course": "B.Tech"


});

// Insert multiple documents

db.students.insertMany([

{ "name": "Bob", "age": 23, "course": "B.Sc" },

{ "name": "Charlie", "age": 24, "course": "BCA" }

]);

2. Read Operation (R)

• The find() method is used to retrieve data from the collection.


• Example:

// Retrieve all documents

db.students.find();

// Retrieve documents with a specific condition

db.students.find({ "course": "B.Tech" });

3. Update Operation (U)

• MongoDB provides the updateOne() method for updating a single document and
updateMany() for multiple documents.
• Example:

// Update a single document

db.students.updateOne(

{ "name": "Alice" },

{ $set: { "age": 23 } }

);

// Update multiple documents

db.students.updateMany(

{ "course": "BCA" },

{ $set: { "age": 25 } }

);

4. Delete Operation (D)

• The deleteOne() method deletes a single document, while deleteMany() removes multiple
documents.
• Example:

// Delete a single document


db.students.deleteOne({ "name": "Bob" });

// Delete multiple documents


db.students.deleteMany({ "course": "B.Sc" });

Conclusion:

CRUD operations in MongoDB allow users to interact with databases efficiently, making data
management flexible and scalable.

25. How does MongoDB ensure data consistency and replication?

Ans.

MongoDB maintains data consistency and high availability through replication and write concerns.
1. Replication in MongoDB

Replication in MongoDB is achieved through Replica Sets, which consist of:

• Primary Node: Handles read and write operations.


• Secondary Nodes: Hold copies of data and sync with the primary.

If the primary node fails, a secondary node automatically takes over, ensuring data availability.

Example of setting up a replica set:

rs.initiate({

_id: "myReplicaSet",

members: [

{ _id: 0, host: "server1:27017" },

{ _id: 1, host: "server2:27017" },

{ _id: 2, host: "server3:27017" }

});

2. Write Concerns for Data Consistency

MongoDB provides write concerns to ensure data integrity. For example, setting w: "majority"
ensures data is written to most nodes before confirming success.

db.students.insertOne(

{ "name": "David", "age": 21 },

{ writeConcern: { w: "majority" } }

);

3. Journaling for Durability

MongoDB uses journaling to recover data in case of crashes by recording operations in a log file.
4. Read Preferences for Load Balancing

MongoDB allows users to distribute read queries among primary and secondary nodes using read
preferences:

db.students.find().readPref("secondary");

Conclusion:

By using replica sets, write concerns, journaling, and read preferences, MongoDB ensures data
consistency, fault tolerance, and high availability in distributed environments.

26. Explain the Aggregation Framework in MongoDB with examples.

Ans.

MongoDB’s Aggregation Framework is used to process data and generate computed results efficiently.
It is similar to SQL’s GROUP BY function but provides additional flexibility.

Key Aggregation Stages

The aggregation pipeline consists of multiple stages, each performing a specific transformation.

1. $match – Filtering Documents

Filters data based on conditions.

db.students.aggregate([

{ $match: { "course": "B.Tech" } }

]);

2. $group – Grouping Data

Groups data and performs aggregate operations like count, sum, avg, etc.

db.students.aggregate([

{ $group: { _id: "$course", total_students: { $sum: 1 } } }

]);
This counts the number of students in each course.

3. $sort – Sorting Documents

Sorts documents based on a specified field.

db.students.aggregate([

{ $sort: { "age": -1 } } // Sorts in descending order

]);

4. $project – Selecting Specific Fields

Projects only specific fields from the document.

db.students.aggregate([

{ $project: { "name": 1, "age": 1, "_id": 0 } }

]);

5. $limit and $skip – Pagination

Used to limit the number of results and skip initial records.

db.students.aggregate([

{ $skip: 5 }, // Skips first 5 documents

{ $limit: 10 } // Limits output to 10 documents

]);

Example of Full Aggregation Pipeline:-

db.sales.aggregate([

{ $match: { "category": "Electronics" } },

{ $group: { _id: "$brand", total_sales: { $sum: "$amount" } } },

{ $sort: { total_sales: -1 } }

]);
This pipeline:

1. Filters sales related to electronics.


2. Groups them by brand and calculates total sales.
3. Sorts the result in descending order of sales.

Conclusion:

The Aggregation Framework in MongoDB allows efficient data processing by filtering, grouping, sorting,
and transforming data within the database, reducing the need for external computations.

---

Unit 3: Express.js & Node.js (Backend Development)


Short Answer (2-5 Marks)

27. What is Express.js, and why is it used?

Ans.

Express.js is a lightweight web application framework for Node.js that simplifies building web
applications and APIs. It provides features like routing, middleware support, and template
engines, making development faster and more efficient.

Uses:

• Creates RESTful APIs easily.


• Handles HTTP requests and responses.
• Manages middleware for authentication, logging, etc.

28. How do you set up a basic Express.js server?

Ans.

To set up a basic Express.js server:

1. Install Express:

npm install express

2. Create a server file (server.js)


const express = require('express');

const app = express();

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

res.send('Hello, World!');

});

app.listen(3000, () => {

console.log('Server running on port 3000');

});

3. Run the server:

node server.js

The server will be available at http://localhost:3000.

29. What is middleware in Express.js?

Ans.

Middleware in Express.js is a function that runs before the final request handler. It processes
requests, modifies responses, and handles errors.

Example:

app.use((req, res, next) => {

console.log('Middleware executed');

next();

});

Types of Middleware:
1. Built-in (e.g., express.json())
2. Custom Middleware (e.g., logging, authentication)
3. Third-party Middleware (e.g., cors, helmet)

30. Differentiate between GET and POST methods in Express.js.

Ans.

31. How do you handle errors in Express.js?

Ans.

Errors in Express.js are handled using error-handling middleware.

Example:

app.use((err, req, res, next) => {

console.error(err.stack);

res.status(500).send('Something went wrong!');

});

To trigger an error manually:

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

next(new Error('Test Error'));

});

Express automatically forwards errors to the error-handling middleware.


32. What is Node.js, and what makes it unique?

Ans.

Node.js is a JavaScript runtime built on Chrome’s V8 engine. It allows JavaScript to run on the
server-side.

Unique Features:

• Non-blocking I/O (handles multiple requests at once).


• Single-threaded Event Loop (efficient resource management).
• Cross-platform (runs on Windows, Linux, and macOS).
• Rich package ecosystem via npm.

Example:

console.log('Hello, Node.js');

33. How does the Event Loop work in Node.js?

Ans.

The Event Loop in Node.js handles asynchronous operations using a single-threaded model.

Phases of the Event Loop:

1. Timers → Executes setTimeout() and setInterval().


2. I/O Callbacks → Handles I/O operations.
3. Idle/Prepare → Internal operations.
4. Poll → Retrieves new I/O events.
5. Check → Executes setImmediate().
6. Close Callbacks → Handles closed connections.

Example:

console.log("Start");

setTimeout(() => console.log("Timeout"), 0);

console.log("End");

Output:

Start
End

Timeout

Even though setTimeout() is set to 0ms, it executes after synchronous code due to the Event
Loop.

34. What is the role of npm in Node.js?

Ans.

npm (Node Package Manager) is used to manage Node.js packages (libraries and
dependencies).

Roles of npm:

• Installs packages (npm install express).


• Manages dependencies via package.json.
• Updates and removes packages (npm update, npm uninstall).
• Provides a registry for open-source packages (https://www.npmjs.com/).

Example:

npm init -y # Initializes a new Node.js project

npm install mongoose # Installs Mongoose package

This allows developers to easily manage third-party modules in Node.js applications.

35. Explain the difference between synchronous and asynchronous programming in


Node.js.

Ans.
Example:

Synchronous (Blocking):

const data = fs.readFileSync('file.txt', 'utf8');

console.log(data);

console.log("This runs after file read.");

Asynchronous (Non-blocking):

fs.readFile('file.txt', 'utf8', (err, data) => {

console.log(data);

});

console.log("This runs before file read.");

In asynchronous, execution continues without waiting, improving performance.

Long Answer (8-10 Marks)

36. Discuss the file system module in Node.js with examples.

Ans.
The File System (fs) module in Node.js allows interaction with the file system, such as reading, writing,
updating, deleting, and renaming files. It provides both synchronous (blocking) and asynchronous (non-
blocking) methods.

1. Importing the fs Module:

const fs = require('fs');

2. Reading a File:

• Synchronous (Blocking):

const data = fs.readFileSync('example.txt', 'utf8');

console.log(data);

• Asynchronous (Non-blocking):

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) throw err;
console.log(data);
});

3.Writing to a File:

fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {

if (err) throw err;

console.log('File written successfully!');

});

4. Appending to a File:

fs.appendFile('example.txt', '\nThis is an appended text.', (err) => {


if (err) throw err;
console.log('Text appended successfully!');
});

5. Deleting a File:

fs.unlink('example.txt', (err) => {


if (err) throw err;
console.log('File deleted!');
});
6. Creating and Removing Directories:

fs.mkdir('myFolder', (err) => {


if (err) throw err;
console.log('Folder created!');
});

fs.rmdir('myFolder', (err) => {


if (err) throw err;
console.log('Folder removed!');
});

Conclusion:

The fs module is essential for handling files and directories in Node.js applications, enabling server-side
file management efficiently.

37. Explain how to build RESTful APIs using Node.js and Express.js.

Ans.

A RESTful API (Representational State Transfer API) is a web service that follows REST principles. It
allows clients to interact with a server using HTTP methods like GET, POST, PUT, DELETE.

Steps to Build a RESTful API Using Express.js:


1. Install Node.js and Express.js:

npm init -y # Initialize a Node.js project

npm install express body-parser mongoose cors # Install required dependencies

2. Set Up an Express Server:

const express = require('express');


const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON

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


res.send('Welcome to REST API');
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});

3. Define RESTful Routes:

const users = [{ id: 1, name: "John Doe" }];

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

res.json(users);

});

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

const newUser = req.body;

users.push(newUser);

res.status(201).json(newUser);

});

4. Test the API Using Postman or Browser:

• GET request to /users → Retrieves users.


• POST request to /users with JSON body → Adds a new user.

Conclusion:

Using Express.js, we can easily build a scalable, maintainable, and lightweight RESTful API that
communicates with databases like MongoDB.

38. How does Node.js handle asynchronous operations?

Ans.

Node.js is asynchronous and non-blocking, making it efficient for handling multiple requests. It achieves
this through:
1. Callback Functions (Old Approach)

fs.readFile('example.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log(data);

Here, the callback function runs after file reading is complete.

2. Promises (Improved Approach)

const fs = require('fs').promises;

fs.readFile('example.txt', 'utf8')

.then(data => console.log(data))

.catch(err => console.log(err));

Promises make asynchronous code cleaner and easier to manage.

3.Async/Await (Modern Approach)

const readFileAsync = async () => {

try {

const data = await fs.readFile('example.txt', 'utf8');

console.log(data);

} catch (err) {

console.log(err);

};

readFileAsync();

async/await makes asynchronous code look synchronous, improving readability.


4. Event Loop in Node.js

Node.js handles asynchronous operations using an event loop, which:

• Processes I/O operations in the background.


• Executes callbacks when operations are complete.

Conclusion:

Node.js uses callbacks, promises, async/await, and the event loop to handle asynchronous tasks
efficiently.

39. How do you integrate MongoDB with an Express.js server?

Ans.

To integrate MongoDB with Express.js, we use Mongoose, an ODM (Object-Document Mapper).

1. Install MongoDB and Mongoose:

npm install mongoose

2. Connect to MongoDB in Express.js:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {

useNewUrlParser: true,

useUnifiedTopology: true

}).then(() => console.log('MongoDB Connected'))

.catch(err => console.log(err));

3.Define a Mongoose Schema and Model:

const userSchema = new mongoose.Schema({

name: String,
email: String

});

const User = mongoose.model('User', userSchema);

4. Create CRUD API Endpoints:

app.post('/users', async (req, res) => {

const newUser = new User(req.body);

await newUser.save();

res.status(201).json(newUser);

});

Conclusion:

MongoDB integration with Express.js is done using Mongoose, enabling a structured way to interact
with databases.

40. How do you implement authentication in a Node.js application?

Ans.

User authentication ensures only authorized users can access resources. It can be implemented
using JWT (JSON Web Token).

1. Install Required Packages:


npm install express jsonwebtoken bcryptjs mongoose

2. Hash Passwords Using bcrypt.js:


const bcrypt = require('bcryptjs');

const hashPassword = async (password) => {


const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(password, salt);
};

3. Generate JWT Token for Authentication:


const jwt = require('jsonwebtoken');

const generateToken = (user) => {


return jwt.sign({ id: user._id }, 'secretKey', { expiresIn: '1h' });
};

4. Protect Routes Using Middleware:


javascript
Copy
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization');
if (!token) return res.status(401).json({ message: 'Access Denied' });

try {
const decoded = jwt.verify(token, 'secretKey');
req.user = decoded;
next();
} catch (err) {
res.status(400).json({ message: 'Invalid Token' });
}
};

Conclusion:

Using bcrypt.js for hashing passwords and JWT for authentication, we can secure Node.js applications
effectively.

---

Unit 4: Angular (Frontend Development)


Short Answer (2-5 Marks)

41. What is Angular, and how does it differ from AngularJS?

Ans.

Angular is a TypeScript-based front-end framework developed by Google for building single-


page applications (SPAs).
42. Define components and modules in Angular.

Ans.

Components: The building blocks of an Angular application that control a section of the UI.
Each component has an HTML template, CSS, and a TypeScript file.

@Component({

selector: 'app-example',

templateUrl: './example.component.html',

styleUrls: ['./example.component.css']

})

export class ExampleComponent {}

Modules: A way to organize an application into smaller, reusable sections. The main module is
AppModule (app.module.ts), where all components and dependencies are declared.

@NgModule({

declarations: [ExampleComponent],

imports: [BrowserModule],

bootstrap: [AppComponent]

})

export class AppModule {}


43. How do you create a new Angular application?

Ans.

To create a new Angular application, follow these steps:

1. Install Angular CLI (if not installed):

npm install -g @angular/cli

2. Create a new Angular project:

ng new my-angular-app

3. Navigate into the project folder:

cd my-angular-app

4. Start the development server:

ng serve

5. Open the browser and go to http://localhost:4200.

44. What is data binding in Angular?

Ans.

Data binding is the process of connecting the application’s data with the UI. Angular provides
four types of data binding:

1. Interpolation ({{}}) – Binds a variable to the template.

<h1>{{ title }}</h1>

2. Property Binding ([]) – Binds a property of an element to a variable.

<input [value]="username">

3. Event Binding (()) – Binds an event to a method.

<button (click)="showMessage()">Click Me</button>

4. Two-Way Binding ([()]) – Synchronizes data between the component and the view.
<input [(ngModel)]="username">

45. What is the purpose of services in Angular?

Ans.

Services in Angular are used to share data and logic across multiple components. They handle
API calls, business logic, and state management.

Example of a simple Angular service:

typescript
Copy
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item1', 'Item2', 'Item3'];
}
}

Services are injected into components using dependency injection, ensuring code reusability
and modularity.

Long Answer (8-10 Marks)

46. Discuss the lifecycle of an Angular component.

Ans.

Angular components go through different lifecycle hooks, which help manage the component’s
behavior from creation to destruction. These hooks are defined in the @Component class using lifecycle
methods.

Lifecycle Hooks in Angular:

1. ngOnInit() – Executed when the component is initialized. Used for fetching data.
2. ngOnChanges() – Called when input properties change.
3. ngDoCheck() – Detects custom changes in the component.
4. ngAfterContentInit() – Runs after projecting content into the component.
5. ngAfterContentChecked() – Called after every content check.
6. ngAfterViewInit() – Runs after the component’s view has been initialized.
7. ngAfterViewChecked() – Executes after each change detection cycle.
8. ngOnDestroy() – Used for cleanup tasks before destroying the component.

Example:
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log("Component Initialized");
}
ngOnDestroy() {
console.log("Component Destroyed");
}
}

47. Explain the different types of data binding in Angular with examples.

Ans.

Data binding is the process of connecting the application’s data to the user interface (UI). There
are four types of data binding in Angular:

1. Interpolation ({{ }}) – One-way binding


o Binds a variable from the component to the template.

Html:-
<h1>{{ message }}</h1>

Typescript:-
export class ExampleComponent {
message = "Hello, Angular!";
}

2. Property Binding ([ ]) – One-way binding


o Binds a property of an element to a variable.

Html:-
<input [value]="username">

Typescript:-
username = "Kaushal";

3. Event Binding (( )) – One-way binding


o Binds an event to a method in the component.

Html:-
<button (click)="showMessage()">Click Me</button>

Typescript:-
showMessage() {
alert("Button clicked!");
}

4. Two-Way Binding ([( )])


o Synchronizes data between the component and the view.

Html:-
<input [(ngModel)]="username">
<p>Hello, {{ username }}</p>

Typescript:-
username = "";

48. How do you implement routing in an Angular application?

Ans.

Routing in Angular is managed by the Angular Router, which enables navigation between different
components in a Single Page Application (SPA).

Steps to Implement Routing in Angular:

1. Import RouterModule in app.module.ts

typescript
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppModule {}

2. Define Router Outlet in app.component.html

html
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
3. Create Components and Use Routes
o Run ng generate component home and ng generate component about to
create components.

Now, when users navigate to /home or /about, Angular loads the respective components.

49. What is dependency injection in Angular?

Ans.

Dependency Injection (DI) is a design pattern used in Angular to manage dependencies efficiently. It
allows Angular to inject services and dependencies into components, making them more modular and
reusable.

Key Benefits of Dependency Injection:

• Reduces tight coupling between components.


• Improves testability by allowing mock dependencies.
• Enhances reusability and code efficiency.

Example of Dependency Injection in Angular:

1. Create a Service (data.service.ts)

Typescript

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Apple', 'Banana', 'Cherry'];
}
}

2. Inject Service into a Component (app.component.ts)

Typescript

import { Component } from '@angular/core';


import { DataService } from './data.service';

@Component({
selector: 'app-root',
template: `<ul><li *ngFor="let item of data">{{ item }}</li></ul>`
})
export class AppComponent {
data: string[];
constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}
}

50. Compare MEAN Stack with LAMP Stack.

Ans.

Both MEAN and LAMP stacks are widely used for web development but differ in technologies
and architecture.

Conclusion:

• MEAN Stack is best for building single-page applications (SPA) and real-time apps (like chat
applications).
• LAMP Stack is suitable for traditional web development (like blogs, CMS, and e-commerce
sites).
Unit 5: Integration, Deployment & Best Practices
Short Answer (2-5 Marks)

51. How do you integrate an Angular frontend with an Express.js API?

Ans.

To integrate an Angular frontend with an Express.js API, follow these steps:

1. Create an Express.js Backend


o Set up a REST API using Express.js.

javascript

const express = require('express');


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

app.use(cors()); // Enable CORS for cross-origin requests


app.use(express.json());

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


res.json({ message: "Hello from Express API!" });
});

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

2. Make HTTP Requests from Angular


o Use HttpClientModule in Angular to consume the API.

typescript

import { HttpClient } from '@angular/common/http';


import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-home',
template: `<p>{{ data?.message }}</p>`
})
export class HomeComponent implements OnInit {
data: any;
constructor(private http: HttpClient) {}

ngOnInit() {
this.http.get('http://localhost:3000/api/data').subscribe(response
=> {
this.data = response;
});
}
}
3. Enable CORS in Express to allow Angular to access the API.
4. Run Both Servers (ng serve for Angular and node server.js for Express).

52. What are the different methods for handling real-time data in a MEAN stack
application using WebSockets?

Ans.

In a MEAN stack application, real-time data is handled using WebSockets, primarily through Socket.io.

Methods for Real-Time Data Handling:

1. Using Socket.io (Recommended for MEAN Apps)


o Server-side (server.js):

javascript

const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('User connected');
socket.emit('message', 'Welcome to real-time updates!');
});

o Client-side (Angular):

Typescript

import { io } from 'socket.io-client';


const socket = io('http://localhost:3000');
socket.on('message', (msg) => console.log(msg));

2. Using Firebase Realtime Database


o Firebase provides real-time syncing of data across users.
3. Using Server-Sent Events (SSE)
o SSE allows the server to push updates to clients without continuous polling.
4. Using Polling (Less Efficient)
o The client requests data at regular intervals, leading to higher server load.

For real-time apps like chat applications, live notifications, or collaborative tools, Socket.io is the best
option in a MEAN stack application.

Long Answer (8-10 Marks)


53. Explain authentication and user management integration in a MEAN stack application.
How do you implement JWT-based authentication?

Ans.

Authentication in a MEAN stack application ensures secure access to resources. JWT (JSON Web Token)
is commonly used for authentication.

Steps to Implement JWT Authentication:

1. User Registration: Store hashed passwords using bcrypt.js.


2. User Login: Verify credentials and generate a JWT token.
3. Protected Routes: Middleware verifies JWT before granting access.

Example (Express.js Backend):

Javascript

const jwt = require('jsonwebtoken');

app.post('/login', async (req, res) => {


const user = await User.findOne({ username: req.body.username });
if (!user || !(await bcrypt.compare(req.body.password, user.password))) {
return res.status(400).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user._id }, 'secretkey', { expiresIn:
'1h' });
res.json({ token });
});

// Middleware for authentication


const authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ message: 'Unauthorized' });
jwt.verify(token, 'secretkey', (err, decoded) => {
if (err) return res.status(401).json({ message: 'Invalid Token' });
req.user = decoded;
next();
});
};

Angular Frontend:

• Send login requests via HttpClient.


• Store the JWT in localStorage and include it in headers for protected API calls.

54. Discuss error handling and testing strategies in a MEAN stack project. How can
Express.js handle errors efficiently?
Ans.

Error Handling in Express.js:

1. Global Error Handling Middleware:

javascript

app.use((err, req, res, next) => {


console.error(err.message);
res.status(500).json({ error: 'Internal Server Error' });
});

2. Try-Catch for Async Errors:

javascript

app.post('/register', async (req, res, next) => {


try {
// Registration logic
} catch (err) {
next(err);
}
});

3. Handling 404 Errors:

javascript

app.use((req, res) => res.status(404).json({ error: 'Not Found' }));


Testing Strategies:

1. Unit Testing:
o Backend: Mocha, Jest, or Chai for testing APIs.
o Frontend: Jasmine & Karma for Angular component testing.
2. Integration Testing:
o Use Supertest to test API routes.
3. End-to-End Testing (E2E):
o Use Cypress or Protractor for UI testing.
4. Mock Database Testing:
o Use MongoDB in-memory for testing queries.

Example Mocha API Test:

Javascript

const request = require('supertest');


const app = require('../server');

describe('GET /dashboard', () => {


it('should return dashboard data', async () => {
const res = await request(app).get('/dashboard');
expect(res.status).toBe(200);
});
});

55. What are the best practices for deploying a MEAN stack application? Explain security,
performance optimization, and CI/CD (Continuous Integration & Deployment).

Ans.

1. Security Best Practices:

• Use Environment Variables: Store sensitive data securely.


• Enable CORS Securely: Restrict API access.
• Input Validation: Use express-validator to prevent SQL/NoSQL injections.
• Enable HTTPS & Use Helmet.js:

javascript

const helmet = require('helmet');


app.use(helmet());

• Rate Limiting: Prevent DDoS attacks.

javascript

const rateLimit = require('express-rate-limit');


app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }));
2. Performance Optimization:

• Use Indexing in MongoDB for fast queries:

javascript

db.users.createIndex({ email: 1 });

• Enable Gzip Compression in Express.js:

javascript

const compression = require('compression');


app.use(compression());

• Lazy Loading in Angular: Load modules on demand.


• Use a Reverse Proxy (Nginx) for better request handling.
3. CI/CD (Continuous Integration & Deployment):

1. Version Control: Use GitHub/GitLab for managing code.


2. Automated Testing: Run tests with Jenkins/GitHub Actions.
3. Docker for Containerization:
o Create a Dockerfile and deploy with Docker Compose.
4. Cloud Deployment:
o Backend: Deploy on AWS EC2, Heroku, or DigitalOcean.
o Frontend: Use Netlify or Vercel.

By following these best practices, a MEAN stack application remains secure, scalable, and optimized for
production environments.

You might also like