As a full-stack JavaScript solution, MERN enables developers to work with just one language, JavaScript, for both the client-side and server-side front-end. This facilitates the transition between client-side and server-side work, increases productivity, and streamlines the development process. Learn from basics to deployment in this MERN Stack Development Tutorial. Launch your web developer career with our MERN Stack Course Syllabus.
Getting Started to MERN
Building entire web applications using the MERN stack allows you to manage everything from the database and server logic to the user experience. We cover the important concepts that help you to learn the MERN tutorial from scratch.
Java Fundamentals
It is important to get acquainted with JavaScript fundamentals. Make sure you are proficient with the following:
- Variables: var, let, const.
- Primitive Data Types: String, Number, Boolean, Null, Undefined, Symbol, and BigInt.
- Reference Data Types: Object, Array, Function.
- Operators: Arithmetic, Comparison, Logical, Assignment, and Others.
- Control Flow: Conditional Statements (if, else if, else, switch), Loops (for, while, do-while, for-in, for-of).
- Functions: Defining, Calling, Scope, Arrow Functions.
- Objects: Create, Access, and this keyword.
- Arrays: Creating and Manipulating. Common Array Methods (push, pop, shift, unshift, slice, splice, mop, filter, and reduce).
- Asynchronous JavaScript: Callbacks, Promises (async, wait).
- ES6+ Features: Template Literals, Destructing, Spread and Rest, Classes, Modules (import / export).
Don’t worry if you are new to these concepts. You can check out our JavaScript course in Chennai to learn the basics.
MongoDB Basics for MERN Stack
MongoDB is a document-oriented, NoSQL database that uses adaptable documents that resemble JSON to store data.
Documents:
- The fundamental MongoDB data unit.
- Holding key-value pairs, much as JSON objects.
- Various data types, such as arrays and other documents, can be used as values.
Example:
{
“_id”: ObjectId(“64578a2b3e9a5c1d7f0b2a1e”),
“name”: “Alice”,
“age”: 30,
“city”: “New York”,
“hobbies”: [“reading”, “hiking”]
}
Each document is uniquely identified by its unique key, _id. If you don’t supply one, MongoDB will create this for you automatically.
Collections:
- MongoDB document groups.
- Comparable to relational database tables.
- Documents in the same collection may have different fields because collections do not impose a schema.
Databases:
- A container for collections.
- A single MongoDB server can house several databases.
Key MongoDB Operations (CRUD):
The core actions you’ll carry out on your data are Create, Read, Update, and Delete, or CRUD for short.
Create (Insert):
insertOne(): One document is added to a collection using insertOne().
db.collection(‘users’).insertOne({ name: “Bob”, age: 25 });
insertMany(): Expands a collection by adding more than one document.
db.collection(‘users’).insertMany([{ name: “Charlie”, age: 35 }, { name: “Dia”, age: 28 }]);
Read (Find):
find(): It pulls documents out of a collection.
To find every document:
db.collection(‘users’).find({});
To find documents matching a query:
db.collection(‘users’).find({ age: { $gt: 25 } }); // Find users older than 25
findOne(): The first document that matches the query is retrieved.
db.collection(‘users’).findOne({ name: “Alice” });
Update:
updateOne(): It updates one document that corresponds to the query.
db.collection(‘users’).updateOne({ name: “Bob” }, { $set: { city: “London” } });
updateMany(): it updates every document that corresponds to the query.
db.collection(‘users’).updateMany({ age: { $lt: 30 } }, { $inc: { age: 1 } }); // Increment age of users younger than 30
Delete:
deleteOne(): It removes the one document that corresponds to the query.
db.collection(‘users’).deleteOne({ name: “Diana” });
deleteMany(): Removes every document that corresponds to the query.
db.collection(‘users’).deleteMany({ city: “New York” });
Connecting MongoDB with Node.js (for MERN):
In a MERN stack application, you will usually need a MongoDB driver to communicate with your MongoDB database from your Node.js/Express.js backend. Examples of such drivers are the standard Node.js driver or Mongoose, an Object Data Modeling library.
Example:
const { MongoClient } = require(‘mongodb’);
// Connection URI
const uri = “mongodb://localhost:27017/mydatabase”; // Replace with your MongoDB connection string
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
console.log(“Connected to MongoDB”);
const db = client.db();
const usersCollection = db.collection(‘users’);
// Example: Inserting a document
const insertResult = await usersCollection.insertOne({ name: “Eve”, age: 32 });
console.log(‘Inserted document =>’, insertResult);
// Example: Finding documents
const findResult = await usersCollection.find({}).toArray();
console.log(‘Found documents =>’, findResult);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
Mongoose: A higher-level abstraction for working with MongoDB is offered by Mongoose. It enables you to specify schemas for your data, which facilitates data validation and management. It is frequently utilized in MERN applications.
Learn more with our MongoDB course in Chennai.
Basics of Express.JS for MERN Stack
Express.js is a quick, neutral, and simple web framework for Node.js. It offers a wide range of functionalities for both mobile and online apps. One Express.js is usually used on the backend (Node.js server) of the MERN stack to manage requests/responses, middleware, and routing.
Installation: Node.js and npm (or yarn) must be installed first. Using npm, you may add Express.js to your project:
npm install express
Basic Server: Here’s a minimal Express.js application:
const express = require(‘express’);
const app = express();
const port = 3000;
app.get(‘/’, (req, res) => {
res.send(‘Hello World!’);
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
- require(‘express’): The Express.js module is imported.
- express(): Generates an application object for Express.
- app.get(‘/’,…): It identifies a route handler that will respond to HTTP GET queries sent to the root path.
- req (request): An object that contains the headers, query parameters, and body of the incoming request.
- res (response): An object used to reply to the client. A fixed response is sent via res.send().
- app.listen(port, …): After starting, it checks for connections on the designated port.
Routing: Routing is the process by which the endpoints (URIs) of an application react to requests from clients. You can specify routes for various HTTP methods (GET, POST, PUT, DELETE, etc.) and URL paths using Express.js.
// Handling a GET request to /users
app.get(‘/users’, (req, res) => {
res.json([{ name: ‘Alice’, age: 30 }, { name: ‘Bob’, age: 25 }]);
});
// Handling a POST request to /users
app.post(‘/users’, (req, res) => {
// Typically, you’d process data sent in the request body here
res.send(‘User created!’);
});
// Route with a parameter
app.get(‘/users/:id’, (req, res) => {
const userId = req.params.id;
res.send(`You requested user with ID: ${userId}`);
});
Middleware: In the request-response cycle of an application, middleware functions are those that have access to the req object, the res object, and the subsequent middleware function. They are capable of a number of activities, including data parsing, authentication, and logging.
// Example of a simple middleware function
const logger = (req, res, next) => {
console.log(`Request received at: ${new Date().toLocaleTimeString()}`);
next(); // Pass control to the next middleware function
};
app.use(logger); // Apply the middleware to all routes
// Middleware specific to a route
const auth = (req, res, next) => {
// For demonstration purposes, always proceed
console.log(‘Authentication check…’);
next();
};
app.get(‘/protected’, auth, (req, res) => {
res.send(‘This is a protected route!’);
});
- Mounting middleware functions at the application level (applied to all routes) is done with app.use().
- To transfer control to the next middleware or the route handler, middleware functions must call the argument they receive next.
Request and Response Objects:
req (Request): Information about the incoming HTTP request is contained in it including:
- req.params: Route parameters.
- req.query: Use the URL’s query parameters (including /items?sort=price).
- req.body: Data transferred in the request body. It requires middleware such as express.json() or express.urlencoded().
- req.headers: HTTP headers.
res (Response): This is used to reply to the client using techniques such as
- res.send(): Provides an HTML or plain text response.
- res.json(): A JSON response is sent using it.
- res.status(code): The HTTP status code is set using it.
- res.render(view, locals): Uses a template engine to render a view.
- res.redirect(url): The client is redirected to another URL with it.
Middleware for Body Parsing:
Body-parsing middleware is required in order to retrieve the data sent in the body of POST or PUT requests (for example, from HTML forms or AJAX calls):
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
How Express.js Fits into MERN:
Express.js, which operates on the Node.js server in a MERN application, is in charge of:
- Establishing API endpoints with which the React frontend can interface.
- Responding to front-end requests.
- Use Mongoose to communicate with the MongoDB database.
- Returning responses(often in JSON format) to the frontend.
Want to learn more about express.JS? Enroll in our full stack developer course in Chennai.
Basics of React JS for MERN Stack Development
Development of the MERN stack requires React.js. It is a JavaScript library for creating UI elements or user interfaces. You can use it to make dynamic and interactive web applications.
JSX (JavaScript XML):
- You can create HTML-like structures in your JavaScript code by using this syntactic extension for JavaScript.
- It is converted into standard calls to JavaScript functions that generate DOM elements.
Example:
const element = <h1>Hello, React!</h1>;
Components:
- Building Blocks: The components of React user interfaces. They are code segments that render to the DOM and are reusable.
- Functional Components: Basic JavaScript functions that return JSX after accepting props (arguments).
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Class Components:
JavaScript classes that extend React.Component and have a render() method that returns JSX are called class components. They may also contain lifespan and state methods.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Props (Properties):
- Data shared between parent and child components.
- From the standpoint of the child component, props are read-only.
function App() {
return <Welcome name=”Sara” />;
}
State:
- It represents information that is subject to change inside a component over time.
- This.state and this are used to handle state within a component, primarily in class components.useState Hook in functional components, or this.setState().
- React re-renders the component when the state changes.
- Using the functional component useState Hook as an example:
import React, { useState } from ‘react’;
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Events:
DOM events are handled differently in React. Functions are passed as event handlers, and event handlers are written in camelCase.
function handleClick() {
console.log(‘Button was clicked!’);
}
function MyButton() {
return <button onClick={handleClick}>Click Me</button>;
}
Conditional Rendering:
JavaScript’s control flow statements (if, else) and the ternary operator can be used to conditionally generate portions of your user interface (UI) depending on specific criteria.
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
Lists and Keys:
You must give each item in the list a distinct key prop when rendering lists of elements. This facilitates React’s effective DOM updating.
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
function NumberList() {
return <ul>{listItems}</ul>;
}
Forms:
React uses controlled components to manage forms, with React state controlling the values of form elements.
import React, { useState } from ‘react’;
function NameForm() {
const [name, setName] = useState(”);
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
alert(‘A name was submitted: ‘ + name);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type=”text” value={name} onChange={handleChange} />
</label>
<input type=”submit” value=”Submit” />
</form>
);
}
Hooks:
You don’t need to write classes to utilize state and other React capabilities due to hooks.
Some Common Hooks include:
- UseState: To give functional components state.
- useEffect: For carrying out side operations (such as subscriptions and data retrieval).
- useContext: For context access.
How React Fits into MERN:
Your web application’s frontend or client-side is constructed using React in the MERN stack. In order to get, display, and transmit data to the server, it communicates with the backend (Express.js/Node.js).
Learn more with our reactjs course in Chennai.
Basics of Node.JS for MERN Stack Development
The Node.js foundations are pertinent to the creation of the MERN stack. The V8 JavaScript engine in Chrome serves as the foundation for the JavaScript runtime Node.js. It enables server-side JavaScript execution.
JavaScript on the Server:
The main advantage of Node.js for the MERN stack is that it makes development more consistent by enabling the use of JavaScript for both the frontend (React) and the backend.
Event-Driven, Non-Blocking I/O Model:
- An event loop is used by Node.js to manage asynchronous tasks.
- Node.js does not halt the main thread when your application needs to do an I/O action (such as reading a file or sending a network request). Instead, it keeps running other code while registering a callback function.
- The callback is run once the I/O operation is finished.
- Because of this, Node.js is very effective at managing multiple requests at once.
npm (Node Package Manager):
- The Node.js package manager by default is called npm. You can quickly install and utilize its extensive collection of open-source libraries and tools in your Node.js projects.
- Express.js, MongoDB drivers (such as Mongoose), and other backend requirements are installed using npm.
Modules:
You can arrange your code into reusable files with Node.js’s module system.
- CommonJS: CommonJS modules with require() for import and module.exports for export were traditionally used with Node.js.
// moduleA.js
const greeting = “Hello”;
module.exports.greeting = greeting;
// main.js
const moduleA = require(‘./moduleA’);
console.log(moduleA.greeting); // Output: Hello
- ES Modules: Although CommonJS is still often used, more recent iterations of Node.js also support ES Modules through import and export.
Built-in Modules:
Numerous built-in modules in Node.js offer essential features without requiring the installation of additional packages. Among the most significant are:
- http: For building clients and servers for HTTP.
- fs: To communicate with the file system.
- path: For manipulating directory and file paths.
- os: To obtain information about the operating system.
Creating a Basic HTTP Server:
This is an illustration of how to use the built-in http module in Node.js to create a basic HTTP server:
const http = require(‘http’);
const port = 3000;
const server = http.createServer((req, res) => {
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello Node.js Server!\n’);
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Although the http module allows you to create web apps directly, frameworks like Express.js, which we covered earlier, are usually used to make the process easier.
How Node.js Fits into MERN:
Node.js is the runtime environment for your backend application, which is often constructed with Express.js in the MERN stack. Node.js is in charge of:
- Running the server for Express.js.
- Responding to incoming React frontend queries.
- Communicating with the MongoDB database and carrying out the application logic.
- Returning answers to the front end.
The environment in which your server-side JavaScript code executes is essentially provided by Node.js.
Explore our NodeJS course in Chennai for further learning.
Bringing it all together (MERN Integration):
- Connecting the Frontend and Backend: Using React to contact the Express.js API.
- Data Flow: It is the process by which information travels from the Express.js API to the MongoDB database, then back to the React frontend.
- Deployment: How to deploy an application using the MERN stack to a hosting platform.
Explore all software training courses available at SLA.
Conclusion
You now have a hands-on understanding of the fundamental elements of the MERN stack and how they work together to build dynamic web apps in this MERN Stack Development Tutorial. Although this concludes this specific guide, your adventure with MERN is far from over. Kickstart your journey with our MERN Stack course in Chennai.