DEV Community

Cover image for Getting Started with the MEAN Stack
MediaGeneous
MediaGeneous

Posted on

Getting Started with the MEAN Stack

Getting Started with the MEAN Stack

The MEAN Stack is a powerful and popular full-stack JavaScript framework used for building dynamic web applications. It consists of four key technologies:

  • MongoDB – A NoSQL database for storing data.

  • Express.js – A backend web application framework for Node.js.

  • Angular – A frontend framework for building user interfaces.

  • Node.js – A JavaScript runtime for server-side development.

MEAN is a great choice for developers looking to build scalable, high-performance applications using a single programming language (JavaScript) across the entire stack. In this guide, we'll walk through setting up a basic MEAN Stack application from scratch.


Prerequisites

Before diving in, make sure you have the following installed:

  1. Node.js & npm – Download and install from Node.js official website.

  2. MongoDB – Install MongoDB Community Edition from MongoDB’s website.

  3. Angular CLI – Install using npm:

    bashCopyDownload

    npm install -g @angular/cli

Step 1: Setting Up the Backend with Node.js & Express

First, let’s create a new directory for our project and initialize a Node.js application:

bashCopyDownload
mkdir mean-stack-app

cd mean-stack-app

npm init -y

Next, install Express.js and other required dependencies:

bashCopyDownload
npm install express mongoose body-parser cors

Now, create a server.js file to set up a basic Express server:

javascriptCopyDownload
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');

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

// Middleware
app.use(cors());
app.use(bodyParser.json());

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/mean-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));

// Basic Route
app.get('/', (req, res) => {
res.send('MEAN Stack is running!');
});

// Start Server
app.listen(PORT, () => {
console.log(</span><span>Server running on http://localhost:</span><span><span>${</span><span>PORT</span><span>}</span></span><span>);
});

Run the server using:

bashCopyDownload
node server.js

Your backend should now be running on http://localhost:3000.


Step 2: Creating a MongoDB Schema and API Endpoints

Let’s define a simple Task model and create API endpoints for CRUD operations.

Add the following to server.js:

javascriptCopyDownload
// Task Model
const Task = mongoose.model('Task', {
title: String,
description: String,
completed: Boolean,
});

// CRUD Endpoints
// Create a Task
app.post('/tasks', async (req, res) => {
const task = new Task(req.body);
await task.save();
res.send(task);
});

// Get All Tasks
app.get('/tasks', async (req, res) => {
const tasks = await Task.find();
res.send(tasks);
});

// Update a Task
app.put('/tasks/:id', async (req, res) => {
const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(task);
});

// Delete a Task
app.delete('/tasks/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send({ message: 'Task deleted' });
});

Now you have a fully functional REST API for managing tasks!


Step 3: Building the Frontend with Angular

Let’s create a new Angular application for the frontend:

bashCopyDownload
ng new mean-frontend

cd mean-frontend

Install HttpClientModule for API calls:

typescriptCopyDownload
// src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule],
})

Now, generate a TaskService to interact with the backend:

bashCopyDownload
ng generate service services/task

Update task.service.ts:

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

@Injectable({
providedIn: 'root'
})
export class TaskService {
private apiUrl = 'http://localhost:3000/tasks';

constructor(private http: HttpClient) { }

getTasks() {
return this.http.get(this.apiUrl);
}

createTask(task: any) {
return this.http.post(this.apiUrl, task);
}

updateTask(id: string, task: any) {
return this.http.put(</span><span><span>${</span><span>this</span><span>.</span>apiUrl<span>}</span></span><span>/</span><span><span>${</span>id<span>}</span></span><span>, task);
}

deleteTask(id: string) {
return this.http.delete(</span><span><span>${</span><span>this</span><span>.</span>apiUrl<span>}</span></span><span>/</span><span><span>${</span>id<span>}</span></span><span>);
}
}

Finally, create a component to display tasks:

bashCopyDownload
ng generate component task-list

Update task-list.component.ts:

typescriptCopyDownload
export class TaskListComponent implements OnInit {
tasks: any[] = [];

constructor(private taskService: TaskService) { }

ngOnInit() {
this.loadTasks();
}

loadTasks() {
this.taskService.getTasks().subscribe((res: any) => {
this.tasks = res;
});
}

addTask(title: string, description: string) {
this.taskService.createTask({ title, description, completed: false })
.subscribe(() => this.loadTasks());
}

deleteTask(id: string) {
this.taskService.deleteTask(id).subscribe(() => this.loadTasks());
}
}

Update task-list.component.html:

htmlCopyDownloadRun
<div>
<h2>Tasks</h2>
<div *ngFor="let task of tasks">
<h3>{{ task.title }}</h3>
<p>{{ task.description }}</p>
<button (click)="deleteTask(task._id)">Delete</button>
</div>
</div>

Run the Angular app:

bashCopyDownload
ng serve

Visit http://localhost:4200 to see your MEAN Stack app in action!


Conclusion

The MEAN Stack provides a seamless way to build full-stack applications using JavaScript. With MongoDB for data storage, Express & Node.js for the backend, and Angular for the frontend, you can develop scalable and efficient web apps.

If you're looking to grow your YouTube channel while learning web development, consider checking out MediaGeneous for expert strategies to boost your audience.

Now that you’ve built a basic MEAN Stack app, try expanding it by adding user authentication with Passport.js or deploying it to Heroku or AWS. Happy coding! 🚀

Top comments (0)