Industrial Training Report Mern Stack: Submitted in Partial Fulfilment of The Requirement For The Award of Degree of
Industrial Training Report Mern Stack: Submitted in Partial Fulfilment of The Requirement For The Award of Degree of
BACHELOR OF TECHNOLOGY
Yashasvi Agrawal
B. TECH VII Semester
ii
I confirm that this work has not been previously submitted for any other purpose.
ACKNOWLEDGEMENT
“There are times when silence speaks so much more loudly than words of praise
to only as good as be little person, whose words do not express, but only put a
veneer over true feelings, which are of gratitude at this point of time.”
“Presentation, inspiration and motivation have always played a key role in the
success of any venture.”
Last, but not the least, my parents are also an important inspiration for me and
also like to thank all those who directly or indirectly helped me throughout my
work. So, with due regards, I express my gratitude to them.
Yashasvi Agrawal
20EAIIT020
iv
Table Of Content
1.1 History
The history of the MERN stack revolves around the evolution and integration of its core
technologies—MongoDB, Express.js, React, and Node.js—each with its own distinct timeline.
● Node.js (2009): Node.js was introduced by Ryan Dahl in 2009. It marked a significant
shift by allowing JavaScript to be used for server-side programming. Its non-blocking,
event-driven architecture appealed to developers seeking more efficient ways to build
scalable applications.
● Express.js (2010): Express.js emerged in 2010 as a minimalist web application
framework for Node.js. It simplified the process of building web applications by
providing robust features for routing, middleware creation, and handling HTTP
requests.
● React.js (2013): Developed by Facebook, React.js was released in 2013. It
revolutionized frontend development by introducing a component-based architecture
and the concept of a virtual DOM, enhancing performance and reusability in UI
development.
● MongoDB (2009): MongoDB, released in 2009, offered a different approach to
database management. It departed from traditional relational databases by employing a
1
flexible, document-based data model, making it easier to work with data in the
JSONlike format.
React seamlessly integrates with backend APIs, enabling smooth data flow between the
frontend and backend layers. Its modular approach fosters code reusability, scalability, and
maintainability, making it an ideal choice for crafting complex and responsive interfaces.
Additionally, React's extensive ecosystem of tools and libraries facilitates the development of
Single Page Applications (SPAs) and rich web applications, ensuring a streamlined
development process.
Together, Node.js and Express.js facilitate the creation of RESTful APIs, manage server
operations, and ensure seamless communication between the frontend and the database,
typically MongoDB in the MERN stack. This backend setup enables the development of
scalable, data-intensive applications while maintaining flexibility and performance.
2
The MERN stack's relevance in modern web development stems from its holistic approach,
uniting MongoDB's flexibility, Express.js's streamlined server-side operations, React's
dynamic user interfaces, and Node.js's server-side JavaScript execution. Its core advantage lies
in leveraging JavaScript throughout the development cycle, promoting code coherence and
versatility. This unity simplifies data transfer between frontend and backend, facilitating agile
and responsive application development.
The stack's adaptability to handle complex, real-time data and its scalability make it a go-to
choice for developers aiming to create robust, high-performance web applications. Its unified
ecosystem minimizes compatibility issues and offers a wide array of libraries and tools,
fostering rapid development cycles. Embraced by a thriving community, the MERN stack
remains pivotal in modern development paradigms, empowering developers to craft
sophisticated, data-centric applications while ensuring flexibility, efficiency, and
maintainability across the entire development spectrum.
● Web Application Development: MERN is widely employed for developing web applications
across diverse domains, including e-commerce, social media, content management systems,
and more. Its robustness in handling real-time data, scalability, and responsiveness makes it
ideal for creating dynamic, data-driven web applications.
● Startups and Small Businesses: Due to its open-source nature, ease of learning, and
comprehensive ecosystem, the MERN stack is popular among startups and small businesses.
It enables rapid prototyping, quicker development cycles, and cost-effective solutions for
establishing online platforms.
● Enterprise Solutions: Large-scale enterprises leverage the MERN stack to build scalable,
enterprise-grade applications. Its ability to handle complex functionalities, coupled with its
performance and scalability features, makes it suitable for mission-critical applications
within organizations.
3
● Real-time Applications: MERN's event-driven architecture, particularly with Node.js, is
well-suited for building real-time applications like chat applications, live streaming
platforms, collaborative tools, and IoT applications. Its ability to handle multiple concurrent
connections efficiently is advantageous for such applications.
● Cross-platform Development: React Native, which utilizes React.js, allows developers to
build cross-platform mobile applications using the same codebase as the web application.
This reusability significantly reduces development time and effort for both web and mobile
platforms.
● Data-intensive Applications: MongoDB's document-based structure in the MERN stack
makes it ideal for handling large volumes of unstructured or semi-structured data. It's used
in applications requiring flexible data models, such as content management systems or
applications dealing with user-generated content.
● Innovation and Rapid Development: The MERN stack's unified JavaScript ecosystem
encourages innovation and experimentation. It facilitates quick iteration, enabling
developers to bring new features to market faster and stay agile in an ever-evolving digital
landscape.
Agile Development: MERN is well-suited for Agile methodologies like Scrum or Kanban. Its
modular structure allows teams to work in sprints, iteratively building and testing components,
ensuring flexibility to adapt to changing requirements.
Iterative Development: With its modular nature, the MERN stack supports iterative
development. Developers can continuously enhance features, adding or modifying components
in an incremental manner while ensuring the application remains functional and maintainable.
Test-Driven Development (TDD): Using testing frameworks like Jest for React and
Mocha/Chai for Node.js, developers can adopt a test-driven approach. They write tests first,
then write code to pass those tests, ensuring code reliability and facilitating future
modifications.
4
Component-Based Development: Given React's component-based architecture, a methodology
centered around building and reusing modular UI components is common. This promotes code
reusability, maintainability, and easier collaboration among developers.
Scalability-Oriented Design: Node.js' non-blocking I/O and MongoDB's scalability allow for a
methodology focused on scalability. Developers design applications to handle increasing loads
efficiently, emphasizing scalability from the initial stages.
Microservices Architecture: While not strictly a methodology, MERN can be used within a
microservices architecture. Each component (MongoDB, Express.js, React, and Node.js) can
be encapsulated into microservices, promoting flexibility and scalability in complex systems.
It's important to note that the choice of methodology often depends on project requirements,
team preferences, and the specific needs of the application being developed. Teams might adopt
a hybrid approach or customize methodologies to best fit the MERN stack's capabilities and
the project's objectives.
5
Development:
● Creating the application's components using React.js for the frontend and implementing
server-side logic with Node.js and Express.js.
● Integrating MongoDB to handle data storage and retrieval, creating APIs for
communication between frontend and backend.
Testing:
● Conducting unit tests, integration tests, and end-to-end tests to ensure functionality,
performance, and compatibility across the MERN components.
● Employing testing frameworks like Jest, Mocha, or Enzyme for React and Node.js testing.
2. MongoDB
MongoDB, a prominent NoSQL database, diverges from traditional relational databases by
employing a schema-less approach. Its document-based structure and scalability make it ideal
for managing unstructured data, facilitating high performance and adaptability in modern
application development within the MERN stack.
6
semi-structured data seamlessly. MongoDB's architecture revolves around collections of
documents, where each document can have its own unique structure.
This database system boasts high scalability, allowing for distributed architectures and
horizontal scaling across clusters. It excels in handling large volumes of data, making it a
preferred choice for applications requiring flexibility in data modeling and real-time analytics.
MongoDB's rich query language and indexing capabilities facilitate efficient data retrieval and
manipulation. With its versatility, scalability, and capability to handle complex data models,
MongoDB has emerged as a cornerstone in modern application development, playing a pivotal
role in the MERN stack's backend infrastructure.
1. Flexible Schema:
● Documents can have varying structures within the same collection, offering schema
flexibility.
● Fields can be added or modified without requiring changes to other documents, facilitating
easy adaptation to evolving data models.
7
2. BSON Format:
● BSON (Binary JSON) is MongoDB's binary-encoded serialization of JSON-like
documents, providing efficient storage and data retrieval.
● Supports various data types, including strings, numbers, arrays, and nested documents.
3. Document Hierarchy:
● Documents can have nested structures, allowing for complex and hierarchical data models.
● This nesting capability reflects real-world relationships more naturally than traditional
table-based structures.
4. Atomic Operations:
● MongoDB supports atomic operations on single documents, ensuring consistency and data
integrity.
● Updates within a single document are atomic, preventing inconsistencies in data
modifications.
6. Schema Evolution:
● Facilitates dynamic schema changes, allowing applications to evolve without disrupting
existing data.
● Enables seamless modifications to adapt to changing business needs or application
requirements.
7. Rich Querying:
8
● MongoDB's query language (MongoDB Query Language - MQL) supports complex queries,
filtering, and aggregations, empowering efficient data retrieval and manipulation.
The document-oriented nature of MongoDB empowers developers to work with data in a more
intuitive and adaptable manner, allowing for agile and flexible application development.
2. Document Structure:
● Design documents that represent entities or objects within the application. Each document
typically corresponds to a record or an entity.
● Utilize embedded documents and arrays to represent complex relationships and hierarchical
data.
4. Data Consistency:
9
● Ensure consistency within documents. Atomic operations on single documents maintain
data integrity.
● Normalize or separate data if frequent updates to a particular subset of fields might lead to
high contention.
6. Scalability Considerations:
● Plan for scalability by considering how data will scale as the application grows.
● Employ sharding strategies, distribute data across shards, and leverage replica sets for
redundancy and fault tolerance.
7. Iterative Approach:
● Refine the data model iteratively based on real-world usage and feedback, adjusting as the
application evolves.
● MongoDB's flexibility allows for agile schema design and data modeling, enabling
developers to tailor structures to specific application needs, optimize performance, and
accommodate changes over time without compromising efficiency.
10
3. Express.js
Express.js, a Node.js web application framework, simplifies backend development with
streamlined route handling and middleware management. Its lightweight nature and extensive
middleware support enable rapid API and web app creation, making it a popular choice for
scalable and efficient server-side architectures.
11
Express.js embraces JavaScript, fostering a modular and organized approach to backend
development. It enables the construction of efficient server-side architectures, leveraging
Node.js's event-driven paradigm to manage asynchronous operations efficiently. This
framework's extensive middleware support extends its functionality, allowing developers to
easily integrate additional features like authentication, logging, and error handling.
The vibrant community and an expansive ecosystem of third-party middleware and plugins
further enhance Express.js's appeal. Its adaptability and customizable nature make it a preferred
choice for developers seeking agility and performance in building APIs and web applications
within the Node.js environment. Express.js stands as a cornerstone for building scalable,
efficient, and feature-rich server-side components within the MERN stack and beyond.
Routing in Express.js:
Express.js routing involves defining endpoints for handling incoming HTTP requests. It
allows developers to map specific URLs (or patterns) to corresponding code that processes
those requests. For instance, a route might handle requests to "/products" by fetching product
data from a database and rendering it on a webpage. Routes can also incorporate parameters,
enabling dynamic URL segments (e.g., "/products/:id") to access specific resources.
Express's robust routing system enables middleware to be attached to specific routes,
12
allowing for authentication checks, logging, or data validation before reaching the route
handler. This modular approach aids in code organization, making applications easier to
maintain and scale.
Middleware in Express.js:
Express.js middleware functions intercept incoming HTTP requests and responses. They sit
between the client request and the server's final response, performing specific tasks such as
authentication, error handling, or logging. Middleware functions are executed in sequence,
and they have access to the request and response objects, enabling manipulation of data or
headers. This powerful feature enables cross-cutting concerns to be addressed uniformly
across routes without duplicating code, enhancing code reusability, maintainability, and
ensuring consistent behavior across the application.
1. Define Routes:
● Use Express.js to define routes that correspond to different HTTP methods (GET, POST,
PUT, and DELETE) and resource endpoints.
13
● For example, /api/users might handle GET requests to retrieve user data, POST requests to
create new users, etc.
5. Resourceful Routing:
● Structure routes and endpoints to represent resources logically, following RESTful
conventions.
● For instance, /api/books for managing books, /api/users for managing users, adhering to
consistent naming conventions.
6. Data Handling:
● Implement logic within route handlers to interact with data sources (such as databases) to
perform CRUD operations on resources.
14
7. Response Formatting:
● Format responses in a consistent and standardized way, often as JSON, to provide clear and
predictable data to clients.
By employing Express.js routing, middleware, and HTTP handling features in alignment with
RESTful principles, developers can create robust, scalable, and well-structured APIs that
facilitate clear communication and interaction between client applications and servers.
.
4. React
React.js is a widely-used JavaScript library that simplifies front-end development by enabling
the creation of reusable UI components. Its component-based architecture, efficient
rendering, and virtual DOM facilitate building interactive, high-performance web
applications.
15
4.2 History of React.js
React.js emerged from a need to streamline front-end development at Facebook. Initially
developed by Jordan Walke, React started as an internal project in 2011 and was first deployed
on Facebook's newsfeed in 2012. It aimed to solve the challenges of efficiently updating
complex UIs. React was open-sourced in 2013, marking its official public release. Its
innovative Virtual DOM concept and component-based architecture revolutionized UI
development, enabling faster rendering by selectively updating components.
Over the years, React has seen significant growth and adoption beyond Facebook. Its
community-driven development, regular updates, and extensive ecosystem have propelled its
popularity. React's influence expanded beyond web development into mobile with React
Native, allowing developers to build cross-platform mobile applications using the same React
principles. As a result, React.js remains a pivotal force in modern front-end development,
continually evolving to meet the demands of scalable and dynamic user interfaces.
Components:
In React, components are reusable, self-contained building blocks that encapsulate a piece of
the user interface along with its behavior. They can be as simple as a button or as complex as
an entire page. Components can be functional or class-based. Functional components are
simpler, relying solely on functions to define the UI, while class components have additional
features like lifecycle methods and state management.
Props (Properties):
Props allow data to be passed from parent to child components, enabling the customization and
dynamic rendering of components. They are read-only and help maintain the immutability of
data in React. Components receive props as function parameters (in functional components) or
as properties of the this.props object (in class components). Props enable components to be
reusable and flexible by providing different data or configurations based on their use within the
application.
State Management:
16
State represents the internal data of a component that can change over time. It allows
components to manage their data independently. State is initialized within the component using
this.state (in class components) or useState hook (in functional components). When state
changes, React re-renders the component, updating the UI to reflect the new state. Stateful
components manage their own data, making them dynamic and interactive.
Mastering components, effectively utilizing props for data flow, and managing state efficiently
are foundational skills in React development. They enable developers to build scalable,
maintainable, and interactive user interfaces.
Virtual DOM:
React's Virtual DOM stands as a pivotal performance optimization tool, acting as a
lightweight, in-memory representation of the actual browser DOM. It serves as a
reconciliation layer between the application's components and the browser, optimizing the
process of updating the user interface. When changes occur within a React application,
instead of directly manipulating the real DOM, React creates a new Virtual DOM tree,
reflecting the updated UI based on the component changes.
The key efficiency of the Virtual DOM lies in React's diffing algorithm. This algorithm
compares the previous Virtual DOM with the newly generated one, identifying the specific
17
parts that have changed. By computing the difference between the two trees, React
determines the minimal set of modifications required to bring the actual DOM up-to-date
with the application's current state. Consequently, it selectively updates only the elements
that have changed, significantly reducing the number of costly and potentially slow
manipulations to the real DOM.
By leveraging the Virtual DOM, React minimizes direct interactions with the browser's
DOM, which is relatively expensive in terms of performance. This optimization technique
leads to a more responsive and efficient rendering process, particularly in applications with
dynamic content or frequent updates, enhancing overall user experience and ensuring
smoother interactions.
React Rendering Process:
React's rendering process involves the creation and management of a Virtual DOM, which
serves as an intermediary step before affecting the actual browser DOM. When a
component's state or props change, React triggers a re-rendering process. It constructs a new
Virtual DOM representation based on the updated state, allowing it to efficiently determine
the differences between the previous and updated Virtual DOMs.
React's diffing algorithm then performs a comparison between these two Virtual DOM
representations, analyzing the changes and computing the minimal set of alterations required
to synchronize the actual browser DOM with the updated state of the application. By
identifying the specific elements that have changed, React strategically updates the real
DOM, optimizing performance by minimizing unnecessary re-renders and DOM
manipulations.
This process enables React to intelligently apply only the necessary changes to the actual
DOM, resulting in enhanced performance and improved rendering speed. By streamlining
the rendering pipeline through the Virtual DOM and intelligent diffing mechanisms, React
ensures efficient updates, reducing the computational overhead associated with frequent
changes and contributing to a more responsive user interface.
18
5. Node.js
Node.js is an open-source, server-side JavaScript runtime environment that allows
developers to execute JavaScript code on the server. It operates outside the browser and
enables the creation of highly scalable and efficient network applications.
19
attributes collectively position Node.js as an ideal framework for building high-
performance, real-time applications, micro services, APIs, and more, offering
developers a versatile tool to craft responsive, scalable, and resource-efficient
applications across diverse domains.
Asynchronous programming:
• Promises introduce a more structured way of dealing with asynchronous operations. They
represent a future value or an eventual result of an asynchronous task, allowing chaining and
handling of success or failure through then() and catch() methods. Promises alleviate callback
nesting issues and simplify error handling, enhancing code readability.
20
pause execution until a Promise settles, this paradigm significantly enhances code clarity,
making it easier to understand and maintain.
Server-side scripting involves executing scripts on the server to generate dynamic content or
respond to client requests. In the context of Node.js, server-side scripting typically involves
writing JavaScript code to handle incoming requests, process data, interact with databases,
and generate dynamic responses.
With Node.js, JavaScript can be used for both client-side and server-side scripting, unifying
the programming language across the entire application stack. This unification streamlines
development workflows, allowing developers to use the same language and coding patterns
on both ends.
In server-side scripting, Node.js leverages its event-driven, non-blocking I/O model. When a
client sends a request, Node.js handles it asynchronously, allowing the server to continue
processing other tasks without waiting for the request to complete. This approach ensures
scalability and responsiveness, making Node.js well-suited for applications that require
handling multiple simultaneous requests, real-time data processing, or I/O-intensive
operations.
Node.js facilitates server-side scripting by providing modules and APIs that enable
developers to create robust, high-performance applications. It allows for the creation of web
servers, APIs, micro services, and various backend functionalities, leveraging JavaScript's
flexibility and Node.js's event-driven architecture to build efficient server-side applications.
21
5.4 Event Driven Architecture
Event-driven architecture (EDA) is a design paradigm where the flow of the system is
determined by events such as user actions, system notifications, or messages from other
components. In an event-driven system, components communicate asynchronously by
generating, capturing, and responding to events.
In the context of Node.js, EDA plays a fundamental role due to its event-driven, non-blocking
I/O model. Node.js employs an event loop that continuously listens for events. When an event
occurs, such as an incoming HTTP request or the completion of a database query, Node.js
triggers the associated event handler or callback function.
This approach allows Node.js applications to be highly responsive and scalable. Instead of
waiting for each task to finish before moving to the next, Node.js can efficiently handle
multiple events concurrently, making it particularly well-suited for I/O-bound tasks where
operations like reading files, making network requests, or interacting with databases occur.
Event-driven architecture enables the development of highly reactive and efficient systems.
It promotes loose coupling between components, as they interact through events, making
applications more modular and easier to maintain. Node.js's event-driven nature is a core
factor in its ability to handle numerous concurrent connections and perform efficiently in
real-time applications, chat systems, streaming services, and more.
22
Download MongoDB:
● Visit the MongoDB website and navigate to the download section.
● Choose the Community Server edition compatible with your Windows version.
● Download the MSI installer.
Install MongoDB:
● Run the downloaded MSI installer.
● Follow the installation wizard's instructions.
● Choose the Complete installation type for a standard setup, or select Custom to
customize the installation path.
● During the setup, select "Install MongoDB as a Service" and check "Run service
as Network Service user."
● Complete the installation process.
Install Node.js:
● Run the downloaded Node.js installer.
● Follow the installation wizard's instructions.
● Accept the license agreement and choose the installation location.
● Click "Next" through the remaining steps and complete the installation.
Verify Node.js Installation:
● Open Command Prompt and type node -v to check the Node.js version.
● Run npm -v to verify that npm (Node Package Manager) is installed along with
Node.js.
23
6.3 Express.js Installation:
Create an Express.js Project:
● Open Command Prompt and create a directory for your Node.js/Express.js
project: mkdir my-express-app.
● Move into the newly created directory: cd my-express-app.
● Initialize your Node.js project with npm: npm init -y. This creates a package.json
file with default settings.
Install Express.js:
● Run npm install express to install the Express.js framework as a dependency for
your project.
24
● Use Mongoose to establish a connection to MongoDB by configuring your
Express.js application to connect to the MongoDB database.
Integrating MongoDB, Node.js/Express.js, and React.js forms the MERN stack, providing a
comprehensive environment to build robust, full-stack web applications on Windows systems.
Adjustments and additional configurations may be necessary based on specific project
requirements and functionalities.
25