Table of Contents
MERN Stack Tutorial
Web development involves creating, building, and maintaining websites, covering areas like design, publishing, programming, and database management. The MERN stack is a popular choice for web development, consisting of MongoDB for data storage, Express.js for server-side logic, React.js for building user interfaces, and Node.js for server-side runtime. This stack offers a comprehensive framework for efficient and scalable web applications.
Definition Of Mern Stack
Mern Stack is basically a Javascript Stack which is more easier and faster deployment of full-stack web applications. Mern Stack consists of 4 technologies which are MangoDB, Express, React and Node.js. Mern stack is structured for making the development process much smoother and easier.
- MongoDB: Non Relational Database
- Express: Node.js web server
- React: JavaScript Frontend Framework
- Node: JavaScript Web Server
How Mernstack will function?
In the MERN stack, developers use React to implement the view layer, while Express and Node handle the application layer. MongoDB is then utilized for the database layer, providing a complete solution for building web applications.
Roadmap For Mern Stack Developer
Step 1: Learn basics of HTML, CSS and JavaScript
Step 2: Learn React which is a frontend library for building User Interfaces
Step 3: Learn Node.js which is JavaScript runtime environment
Step 4: Learn Express.js, a framework built upon Node.js to simplify the process of creating web application and API building
Step 5: Learn MongoDB, a NoSQL database to store and retrieve data from database
How to Install Mern Stack
Step 1: Initially, we have to install a node in our system that will depend upon the operating system.
Step 2: You will require a code editor to work. So, it is necessary to download the code editor. VS Code will be most preferred.
Steps to Install a Mern Stack Project
We have to create a folder structure for both the front end and back end in order to install a Mern Stack Project. Also, the need to define database scheme to store and retrieve data from the database.
Methods to create a basic structure
Your step-by-step guide provides a clear and concise process for setting up a basic MERN stack application. Here’s a summary:
- Create Project Folder: After installing a code editor, create a new project folder. Within this folder, create separate folders for the frontend and backend using commands like
mkdir frontend
andmkdir backend
. - Navigate to Frontend Folder: Move to the frontend folder using the command
cd frontend
. - Initialize React Project: Initiate a React project in the frontend folder using
npx create-react-app
. - Navigate to Backend Folder: Move back to the main project folder and then navigate to the backend folder using commands like
cd..
andcd backend
. - Initialize Backend Project: Initialize the backend project using
npm init -y
. - Install Dependencies: Install necessary backend dependencies (MongoDB, Express, cors, dotenv) using the command
npm i mongodb express cors dotenv
.
Following these steps sets up the basic structure for a MERN stack application, with separate frontend and backend folders. This structure provides a foundation for further development and integration of the frontend and backend components.
What are the components of Mern Stack?
1. MongoDB: Cross-platform Document-Oriented Database
MongoDB is a flexible NoSQL database where data is stored in JSON-like documents. Each document, identifiable by a primary key, forms the basic unit. MongoDB allows users to create databases and tables without a fixed schema. The Mongo shell, a JavaScript interface, facilitates operations like querying and updating records directly from the command line after installation.
Why use MangoDB?
- Fast Indexing: As a document-oriented database, MongoDB allows for efficient indexing of documents, resulting in faster response times.
- Scalability: MongoDB handles large datasets by distributing them across multiple machines, ensuring scalability.
- JavaScript Usage: MongoDB employs JavaScript, providing a significant advantage due to its widespread use and familiarity among developers.
- Schema-less Structure: MongoDB is schema-less, allowing for the storage of various data types in separate documents, providing flexibility.
- JSON Format: Data is stored in the form of JSON, including objects, object members, arrays, values, and strings. JSON syntax is easy to use and widely compatible with browsers.
- Ease of Sharing Data: MongoDB facilitates easy sharing of data of any size and type, including video and audio files.
Note:
It is very easy to set up an Mango DB and very flexible Document Model. It will support document model such as tables, schemes,columns & SQL and is more faster and easier.
Making a database: With the ‘use’ command
use database_name;
Creating a table: If the collection/table is not present , then a new collection/table will be made:
db.createCollection("collection_name");
Adding records into the collection:
db.collection_name.insert
(
{
"id" : 1,
"Name" : "Klaus",
"Department": "Technical",
"Organization": "Skill vertex"
}
);
Querying a document:
db.collection_name.find({Name
: "Klaus"}).forEach(printjson);
2. Express: Back-End Framework:
Express is a framework built on Node.js, streamlining the process of writing back-end code. Instead of dealing with numerous Node modules, Express simplifies the creation of web applications and APIs. It achieves this by supporting various middlewares, enabling developers to write more concise and efficient code. Express is instrumental in designing robust and streamlined back-end solutions for web development.
Why use Express?
Express, being asynchronous and single-threaded, ensures efficiency and scalability. It’s known for its speed and scalability, backed by the largest community in the Node.js ecosystem. Express promotes code reusability through its built-in router and offers a robust API for building web applications and APIs. To initiate an Express project, create a new folder and use a command to set up a package.json
file with default settings.
a.Thereafter, we need to install express by providing the below command and pressing enter. Now, we have to make a file inside the directory with the name index.js
npm install express --save
b.Then, we have to type the given index.js to make a sample server.
const express=require('express'),
http=require('http');
const hostname='localhost';
const port=8080;
const app=express();
app.use((req, res)=> {
console.log(req.headers);
res.statusCode=200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is a test server</h1></body></html>');
});
const sample_server=http.createServer(app);
sample_server.listen(port, hostname, ()=> {
console.log(`Server running at http: //${hostname}:${port}/`);});
c.Then, we need to update the “scripts” section which is in the package.json file.
d. We need to start the server by running the command given below:
npm start
e. Open the browser inorder to receive the output of the running server.
3. React: Front-End Library
React is a tool for making user interfaces using JavaScript. It’s great for building single-page and mobile apps because it handles changing data well. With React, you can use JavaScript to create different parts of the user interface.
Why use React?
- Virtual DOM: Think of it like a clone of the original webpage. Any changes trigger a comparison between this clone and the actual webpage, and updates are made accordingly.
- JSX: Short for JavaScript XML, it’s a simpler way to write React components. It mixes JavaScript with HTML/XML for easier React coding.
- Components: These are the building blocks of React. Each one has its logic, making the whole app easier to understand and promoting code reuse.
- High Performance: React’s Virtual DOM, JSX, and Components make it faster than many other frameworks.
- Developing Apps for Android/iOS: Using React Native, you can code for both Android and iOS with just JavaScript and React knowledge.
- Getting Started: Install “create-react-app” using npm or yarn to kickstart your React application.
npm install create-react-app --global
OR
yarn global add create-react-app
a. Later, Create a new react app with the
create-react-app app_name
b. Go to the ”app_name ” folder and will type yarn start or npm start to begin the application.
c. Then we need to update the index.js file
ReactDOM.render(
<h1>Hello DEVELOPERS!!</h1>,
document.getElementById('root')
);
d. Add the below commands to run the application.
npm start
or
yarn start
4. Node.js: JS Runtime Environment
Node.js enables server-side JavaScript execution, expanding its use beyond browsers. npm, the Node Package Manager, provides access to thousands of free packages (node modules) for seamless integration into projects, enhancing efficiency and functionality.
Why use Node.JS?
- Open-Source Runtime: Node.js is an open-source JavaScript runtime environment.
- Single Threading: It operates on a single-threaded model.
- Data Streaming: Supports efficient data streaming.
- Fast Execution: Utilizes Google Chrome’s JavaScript Engine, resulting in fast code execution.
- High Scalability: Highly scalable for handling concurrent tasks.
- Initialization Command: Start a Node.js application by running a command in the command window, accepting the standard settings.
npm init
a. Make a file with the name index.js
Example: A Basic node can be used to calculate the perimeter and area of rectangle
let rectangle= {
perimeter: (x, y)=> (2*(x+y)), area: (x, y)=> (x*y)
};
function Rectangle(l, b) {
console.log("A rectangle with l = " +
l + " and b = " + b);
if (l <=0 || b <=0) {
console.log("Error! Rectangle's length & "
+ "breadth should be greater than 0: l = "
+ l + ", and b = " + b);
}
else {
console.log("Area of the rectangle: "
+ rectangle.area(l, b));
console.log("Perimeter of the rectangle: "
+ rectangle.perimeter(l, b));
}
}
Rectangle(1, 8);
Rectangle(3, 12);
Rectangle(-6, 3);
Then, we have to run application using the command given below:
npm start
FAQ-MERN Stack Tutorial
1.Is MERN stack for beginners?
Ans. For beginners: The MERN stack is a widely used combination of technologies for creating web applications. If you’re new to web development, you might be curious about the term “tech stack.” Essentially, a tech stack is a set of technologies that work together to build and operate an application.
2. What is MERN full stack?
Ans. The MERN Stack combines four key technologies to create dynamic web applications and websites. Each letter in “MERN” represents a different technology: M for MongoDB, E for ExpressJS, R for ReactJS. Together, these components form a powerful and comprehensive stack for modern web development.
3. Is MERN stack a language?
Ans. The term “MERN stack” refers to a comprehensive JavaScript framework comprising MongoDB, Express.js, React, and Node.js. This stack empowers developers to construct the entire infrastructure of web applications, including the front end, back end, and server components, using the JavaScript programming language.