The MEAN stack, consisting of MongoDB, Express.js, Angular, and Node.js, offers a unified JavaScript-based framework for full-stack web development. This guide helps beginners set up and configure the MEAN stack, covering installation steps, basic components, and creating your first web application.
Web development is essential in today’s digital age, and integral to businesses and daily life. Understanding full-stack development equips developers to handle both front-end and back-end aspects of web applications.
The MEAN stack, comprising MongoDB, Express.js, Angular, and Node.js, is an excellent choice for aspiring full-stack developers. Each component plays a vital role: MongoDB as the database, Express.js as the web application framework, Angular as the front-end framework, and Node.js as the runtime environment.
The MEAN stack is popular for several reasons. It uses JavaScript throughout, simplifying the development process and making switching between different parts of the application easier. This uniformity enhances efficiency, as developers can master one language instead of juggling multiple ones.
The MEAN stack is also known for its scalability, allowing for creating and maintaining large, high-performance applications. Its modular and reusable codebase, supported by a vibrant community, makes it popular among any web development company. By mastering the MEAN stack, beginners can embark on a promising journey into full-stack web development, equipped to create robust and dynamic web applications.
What is MEAN Stack?
Explanation of each component
a) MongoDB: NoSQL database for storing data in JSON-like format.
b) Express.js: Back-end web application framework running on top of Node.js.
c) Angular: Front-end framework for building single-page applications.
d) Node.js: JavaScript runtime built on Chrome’s V8 JavaScript engine.
Prerequisites
a) HTML/CSS: Basic understanding of building web pages.
b) JavaScript: Foundational knowledge of JavaScript, as it’s used throughout the MEAN stack.
c) Optional but recommended: Basic understanding of command-line interface (CLI) and version control (Git).
Setting Up Your Development Environment
How to Install Node.js and npm
- Download the Installer:
- Visit the official Node.js website.
- Download the installer for your operating system (Windows, macOS, or Linux). The LTS (Long-Term Support) version is recommended for most users.
2. Run the Installer:
- Open the downloaded installer file.
- Follow the prompts in the installation wizard.
- Accept the license agreement and choose the installation path.
- Ensure that the option to install npm is selected.
3. Verify the Installation:
- Open your terminal or command prompt.
- Run the following commands to verify the installation:
> node -v
> npm -v
- Code Editor:
Recommendations such as VSCode, and WebStorm.
Useful extensions/plugins.
We’re going to use VSCode(Popular among the most developer)
Learning MongoDB
Basics of NoSQL Databases
Difference between SQL and NoSQL:
Data Model:
- SQL (Structured Query Language): SQL databases are relational, meaning data is stored in structured tables with predefined schemas. Each table consists of rows and columns, and relationships between tables are established using foreign keys. This structure is ideal for complex queries and transactions.
- NoSQL (Not Only SQL): NoSQL databases are non-relational and can handle a variety of data models, including document, key-value, wide-column, and graph formats. MongoDB, a popular NoSQL database, uses a document-oriented model, storing data in flexible, JSON-like documents. This model allows for dynamic schemas and is well-suited for handling unstructured data.
Schema:
- SQL: Requires a fixed schema, meaning the structure of data must be defined before data insertion. Any changes to the schema can be complex and require migration scripts.
- NoSQL: Features a flexible schema, allowing for rapid changes and additions to the data structure without predefined schemas. This makes NoSQL databases more adaptable to evolving data models.
Scalability:
- SQL: Typically scales vertically by adding more power (CPU, RAM) to a single server. Horizontal scaling, which involves adding more servers, is more complex due to the relational nature of the database.
- NoSQL: Designed for horizontal scaling, easily distributing data across multiple servers. This makes NoSQL databases highly scalable and capable of handling large volumes of data and high traffic loads.
Transactions:
- SQL: Supports ACID (Atomicity, Consistency, Isolation, Durability) transactions, ensuring reliable and consistent transactions, making it suitable for applications where data integrity is critical.
- NoSQL: Supports BASE (Basically Available, Soft state, Eventual consistency) transactions, which prioritize availability and partition tolerance over immediate consistency. This approach is suitable for applications that require high availability and can tolerate eventual consistency.
Installing MongoDB
Installation Guide for MongoDB:
Download the Installer:
- Visit the official MongoDB website.
- Select your operating system and download the appropriate installer.
Run the Installer:
- Open the downloaded installer file.
- Follow the installation wizard’s prompts.
- Select the “Complete” installation option for a full setup.
- Opt to install MongoDB as a service, which allows MongoDB to run automatically in the background.
Verify the Installation:
- Open your terminal or command prompt.
- Start the MongoDB server by running:
> mongod
- In a new terminal window, connect to the MongoDB server using the MongoDB shell:
> mongo
- You should see the MongoDB shell prompt, indicating that MongoDB is installed and running correctly.
Learning Express.js
Setting Up Express.js
Creating a Simple Express Application:
- Install Node.js and npm:
- Make sure you have Node.js and npm installed. Verify the installation by running:
> node -v
> npm -v
2. Initialize Your Project:
- Create a new directory for your project and navigate into it:
> mkdir my-express-app
> cd my-express-app
- Initialize a new Node.js project:
> npm init -y
3. Install Express:
- Install Express.js using npm:
> npm install express
4. Create Your Express Application:
- Create an
app.js
file and add the following code to set up a basic Express server:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
5. Run Your Application:
- Start your server:
> node app.js
Open your browser and navigate to http://localhost:3000
. You should see “Hello, World!” displayed.
Middleware and Routing Basics:
Middleware:
- Middleware functions are functions that have access to the request object (
req
), the response object (res
), and the next middleware function in the application’s request-response cycle. They can execute code, make changes to the request and response objects, end the request-response cycle, and call the next middleware function in the stack. - Example:
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
Routing:
- Routing refers to how an application’s endpoints (URIs) respond to client requests. You can define routes to handle different URL paths and HTTP methods.
- Example:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
RESTful API Development
Building and Structuring RESTful APIs:
- Folder Structure:
- Organize your project files for better maintainability:
my-express-app/
├── app.js
├── routes/
│ └── api.js
├── models/
└── controllers/
2. Defining Routes:
- Create a
routes/api.js
file to define your API routes:
const express = require('express');
const router = express.Router();
// Mock data
let items = [{ id: 1, name: 'Item One' }, { id: 2, name: 'Item Two' }];
// GET all items
router.get('/items', (req, res) => {
res.json(items);
});
// GET item by id
router.get('/items/:id', (req, res) => {
const item = items.find(i => i.id == req.params.id);
if (item) {
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// POST create new item
router.post('/items', (req, res) => {
const newItem = { id: items.length + 1, name: req.body.name };
items.push(newItem);
res.status(201).json(newItem);
});
// PUT update item by id
router.put('/items/:id', (req, res) => {
const item = items.find(i => i.id == req.params.id);
if (item) {
item.name = req.body.name;
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// DELETE item by id
router.delete('/items/:id', (req, res) => {
const itemIndex = items.findIndex(i => i.id == req.params.id);
if (itemIndex >= 0) {
items.splice(itemIndex, 1);
res.json({ message: 'Item deleted' });
} else {
res.status(404).json({ message: 'Item not found' });
}
});
module.exports = router;
3. Integrate Routes into Your Application:
- Modify
app.js
to use the defined routes:
const express = require('express');
const app = express();
const apiRoutes = require('./routes/api');
app.use(express.json()); // For parsing application/json
app.use('/api', apiRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Handling Different HTTP Methods (GET, POST, PUT, DELETE):
GET Method:
- Used to retrieve data from the server.
- Example:
router.get('/items', (req, res) => {
res.json(items);
});
router.get('/items/:id', (req, res) => {
const item = items.find(i => i.id == req.params.id);
if (item) {
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
POST Method:
- Used to send data to the server to create a new resource.
- Example:
router.post('/items', (req, res) => {
const newItem = { id: items.length + 1, name: req.body.name };
items.push(newItem);
res.status(201).json(newItem);
});
PUT Method:
- Used to update an existing resource on the server.
- Example:
router.put('/items/:id', (req, res) => {
const item = items.find(i => i.id == req.params.id);
if (item) {
item.name = req.body.name;
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
DELETE Method:
- Used to delete an existing resource from the server.
- Example:
router.delete('/items/:id', (req, res) => {
const itemIndex = items.findIndex(i => i.id == req.params.id);
if (itemIndex >= 0) {
items.splice(itemIndex, 1);
res.json({ message: 'Item deleted' });
} else {
res.status(404).json({ message: 'Item not found' });
}
});
Note: By following these steps, you can set up Express.js, understand middleware and routing basics, and build RESTful APIs that handle different HTTP methods effectively. This will enable you to create scalable and maintainable web applications, providing a solid foundation for any web development project.
Learning Angular
Getting Started with Angular
Installing Angular CLI and Creating a New Project
To get started with Angular, you need to install the Angular CLI (Command Line Interface). This tool allows you to create, build, and manage Angular applications easily. Follow these steps to install Angular CLI and create a new project:
- Install Node.js and npm: Angular requires Node.js and npm (Node Package Manager). Download and install them from Node.js official website.
- Install Angular CLI: Open your terminal or command prompt and run the following command:
> npm install -g @angular/cli
This will install the Angular CLI globally on your system.
Create a New Angular Project: Run the following command to create a new Angular project:
> ng new my-angular-app
Replace my-angular-app
with the name of your project. Follow the prompts to set up your project configuration.
Navigate to the Project Directory: Once the project is created, navigate to the project directory:
> cd my-angular-app
Run the Development Server: Start the development server to see your Angular application in action:
> ng serve
Open your browser and navigate to http://localhost:4200
. You should see the default Angular welcome page.
Angular Components, Modules, and Services
Angular applications are built using components, modules, and services. Understanding these concepts is crucial for developing Angular applications.
- Components: Components are the building blocks of Angular applications. Each component consists of an HTML template, a CSS style, and a TypeScript class. Create a new component using the Angular CLI:
> ng generate component my-component
This command generates a new component with the necessary files and updates the application module.
2. Modules: Modules help organize an application into cohesive blocks of functionality. The root module is AppModule
, which is defined in app.module.ts
. You can create feature modules to encapsulate related components and services:
> ng generate module my-feature
3. Services: Services are used to share data and functionality between components. Create a new service using the Angular CLI:
> ng generate service my-service
Services are typically used for business logic, data retrieval, and other tasks that need to be shared across components.
Data Binding and Component Interaction
Data binding in Angular allows you to synchronize data between the component class and the template. There are different types of data binding:
- One-way Data Binding: One-way data binding binds data from the component to the template. There are two types of one-way data binding:
- Interpolation: Binds data from the component to the template using double curly braces
{{}}
. - Two-way Data Binding: Two-way data binding binds data in both directions, from the component to the template and vice versa. Use the
ngModel
directive for two-way data binding:
Note: By following these steps, you can get started with Angular, create components, bind data, manage component interactions, and make HTTP requests to back-end services. This foundation will help you build robust Angular applications.
For more learning, you can follow AngularDev
Learning Node.js
JavaScript on the Server
Node.js allows you to run JavaScript on the server side, enabling you to build scalable and efficient web applications. Here’s how to get started with a basic setup:
- Setting up a Basic Node.js Server:
- To create a basic Node.js server, follow these steps:
// Import required modules
const http = require('http');
// Define server configuration
const hostname = 'localhost';
const port = 3000;
// Create a server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
// Start the server
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Save this code in a file (e.g., server.js
) and run it using Node.js:
> node server.js
Navigate to http://localhost:3000
in your web browser to see ‘Hello, World!’ displayed.
Understanding Asynchronous Programming
Asynchronous programming is fundamental in Node.js to handle non-blocking operations efficiently. Key concepts include:
- Callbacks: Traditional way of handling asynchronous operations.
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched');
}, 2000);
}
fetchData((data) => {
console.log(data); // Output: Data fetched
});
2. Promises: Introduced to handle asynchronous code more elegantly.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
}
fetchData()
.then((data) => {
console.log(data); // Output: Data fetched
})
.catch((error) => {
console.error(error);
});
3. Async/Await: Syntactic sugar over promises for writing asynchronous code more intuitively.
async function fetchData() {
try {
let data = await fetchData();
console.log(data); // Output: Data fetched
} catch (error) {
console.error(error);
}
}
fetchData();
File System and Streams
Node.js provides modules for file system operations and working with streams for efficient data processing:
- Basic File Operations using Node.js:
- Example of reading and writing files:
const fs = require('fs');
// Reading a file
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Writing to a file
fs.writeFile('newfile.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File created!');
});
2. Streams: Used for efficiently reading or writing large amounts of data.
const fs = require('fs');
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
Integrating with Express
Express.js is a popular framework for building web applications and APIs with Node.js:
- Installing Express:
- Install Express in your Node.js project:
> npm install express
Note: We already have installed the express in our previous learning, now let’s bind both together.
2. Combining Node.js with Express:
Example of setting up a basic Express server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Run the server:
> node server.js
Navigate to http://localhost:3000
in your web browser to see ‘Hello, World!’ displayed.
By mastering these concepts in Node.js, you’ll be able to build robust server-side applications and APIs effectively.