MEAN Stack Simplified: A Beginner’s Guide

Tapesh Mehta Tapesh Mehta | Published on: Mar 04, 2024 | Est. reading time: 10 minutes
MEAN Stack Simplified A Beginner's Guide

The MEAN Stack is an impressive, modern approach to web development that combines four core technologies: MongoDB, Express.js, AngularJS and Node.js. Each component of the MEAN Stack plays a crucial role in web application development. MongoDB is a document database that stores data in a flexible, JSON format which makes it easy to share information between client and server. Express.js, which simplifies the creation of server-side logic and APIs, is a backend web application framework running on Node.js. Angular, a front-end web application framework, allows developers to build dynamic, single page applications with a compelling user interface. Node.js, the JavaScript runtime environment, executes JavaScript code server-side, making application development efficient and scalable.

There are a few advantages to selecting the MEAN Stack for your project. This is an all JavaScript stack that provides a single programming language from client to server and database throughout the development process. This uniformity will facilitate development, reduce context change and increase team productivity. In addition, the MEAN Stack is open source and supported by a large community, offering a wide range of libraries, frameworks, and tools to streamline development. It is an excellent choice for developing a wide range of web applications, from small projects to large scale enterprise solutions, due to its scalability, high performance, and flexibility.

Table of Contents

MEAN Stack: Setting Up the Development Environment

The first step in the MEAN Stack’s implementation is to create a development environment. It involves selecting the right tools and Integrated Development Environments (IDEs) that will make coding more efficient and enjoyable. Visual Studio Code, WebStorm, and Atom are popular IDEs for MEAN Stack development.

Installing Node.js and NPM

The core of the MEAN Stack is Node.js, which allows you to run JavaScript on the server side. NPM is used to manage libraries and packages, included with Node.js. How do you get them set up?

1.  Download Node.js: Go to the official Node.js website and download the installer for your operating system. It’s recommended to download the LTS (Long-Term Support) version for better stability.

2. Install Node.js and NPM: Run the downloaded installer, which will install both Node.js and NPM. Follow the on-screen instructions to complete the installation.

3. Verifying the Installation: Once the installation is complete, open your terminal or command prompt to verify that Node.js and NPM are installed correctly.

node -v

This command checks the installed version of Node.js. You should see the version number if the installation was successful.

npm -v

Similarly, this command checks the installed version of NPM. A version number will confirm a successful installation.

By following these steps, you’ve laid the groundwork for MEAN Stack development. These tools are not only helpful for creating projects, they also provide you with access to a large ecosystem of packages and libraries that can be found on NPM, which makes MEAN Stack applications more powerful.

MEAN Stack: Getting MongoDB Up and Running

As a database component, MongoDB offers a scalable and flexible NoSQL database that stores data in JSON format documents, which is central to the MEAN stack. This compatibility with JavaScript objects enables developers to work with data in the MEAN stack, making it more flexible for clients, servers and databases to sync up.

Installing MongoDB

The installation process for MongoDB varies across different operating systems, but MongoDB provides detailed guides for each. Here’s a general overview:

Windows:

  1. Download the MongoDB installer package from the official MongoDB website.
  2. Run the installer and follow the installation wizard, choosing the “Complete” setup type.
  3. Select “Run service as Network Service user” and take note of the data directory path, as this is where MongoDB will store its databases.
  4. Complete the installation.

macOS:

  1. The easiest way to install MongoDB on macOS is using Homebrew. First, open the Terminal and run:
brew tap mongodb/brew

2. Then, install MongoDB with:

brew install mongodb-community

Linux:

  1. The installation commands vary depending on the Linux distribution. For Ubuntu, you can use:
sudo apt-get update
sudo apt-get install -y mongodb-org

Refer to the MongoDB documentation for instructions tailored to other distributions.

Starting MongoDB Server

To start the MongoDB server, the command differs slightly depending on your operating system:

Windows: Open Command Prompt as an administrator and run:

net start MongoDB

macOS and Linux: Open Terminal and run:

brew services start mongodb-community

Creating Your First Database

Once MongoDB is running, you can interact with it using the MongoDB Shell. Open your terminal or command prompt and enter mongo to start the shell. To create and switch to a new database, use the use command followed by the database name:

use myFirstDatabase

This command creates a new database named myFirstDatabase, if it doesn’t already exist, and switches to it. You can start creating collections and documents within this database, laying the foundation for your MEAN stack application’s data storage.

MEAN Stack: Taking the First Steps with Express.js

Express.js is Node.js’s fast, unopinionated, and minimalist web framework, which serves as the foundation for building web applications and APIs. Express.js plays a critical role in the MEAN stack, by handling server-side logic, routing and MongoDB database interactions that facilitate application development and maintenance.

Setting Up Express.js

To get started with Express.js, you first need to have Node.js and NPM installed on your machine. Here’s how you can set up Express.js:

Create a New Node.js Project: Initialize a new Node.js project by creating a new directory for your project and running the following command in your terminal:

npm init -y

This command creates a package.json file in your project directory, which will keep track of your project’s dependencies.

Installing Express.js: Add Express.js to your project by running:

npm install express

This command downloads Express.js and adds it as a dependency in your package.json file.

Creating a Simple Express Server: Now, let’s create a simple server. Create a file named app.js in your project directory and add the following code:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

This code imports the Express module, creates an Express application, sets up a basic route to respond with “Hello World!” when visiting the root URL, and starts the server on port 3000.

Running Your Server: Start your Express server by running:

node app.js

If everything is set up correctly, you should see a message in your terminal saying that your app is listening at http://localhost:3000. You can open this URL in your browser to see the “Hello World!” message.

Understanding Middleware in Express.js

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. These functions can run any code, change the request and response objects, terminate a request-response cycle or call another middleware function. In order to process requests, read body data, serve static files, and set sessions in Express apps, middleware is essential.

Here’s a simple example of a middleware function that logs the request method and URL:

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass control to the next middleware function
});

In the app.js, copy this snippet prior to your route definition. You will now see the request method and URL registered in your terminal each time you make a request, which demonstrates how middleware functions are able to intercept and process requests within Express.

Angular: The Frontend Framework

Angular is a powerful and versatile frontend framework developed by Google, designed for building dynamic, modern web applications. As a part of the MEAN stack, Angular serves as the layer that handles the user interface, providing a structured and scalable way to build single-page applications with compelling interactive features.

Installing Angular CLI

The Angular CLI (Command Line Interface) is a tool that simplifies the creation, management, and deployment of Angular applications. To install the Angular CLI, you need Node.js and NPM (Node Package Manager) installed on your machine. Once these are in place, open your terminal or command prompt and run the following:

npm install -g @angular/cli

This command installs the Angular CLI globally on your system, allowing you to use it from any directory.

Generating Your First Angular Application

Once the Angular CLI is installed, you can create a new Angular application with just one command. In your terminal or command prompt, navigate to the directory where you want to create your application and run:

ng new my-first-angular-app

Replace my-first-angular-app with your desired project name. This command creates a new folder with the project name, installs all the necessary Angular dependencies, and sets up a default Angular application.

Exploring Angular Components and Modules

Angular applications are structured around components and modules, which help organize the application into cohesive blocks of functionality.

Components are the building blocks of Angular applications. They control a patch of screen called a view. For example, to create a new component named hello-world, you can use the Angular CLI:

ng generate component hello-world

This command generates a new component with four files: a TypeScript file for the component’s logic, an HTML file for the template, a CSS file for the styles, and a testing specification file.

Modules allow you to group components, services, directives and pipes into groups. Every Angular application has at least one module, the root module, typically named AppModule. In order to better organise your code, you can also build more features modules. The following command is used to generate a new module from the CLI:

ng generate module my-module

Replace my-module with your module name. This creates a new module file that you can use to declare the components, directives, and pipes that belong to this module.

MEAN Stack: CRUD Operations with MongoDB and Express.js

First, ensure your Express app is set up to parse JSON bodies. This is crucial for receiving data sent from your Angular frontend.

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

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

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/my_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log("MongoDB connected"))
  .catch(err => console.error("MongoDB connection error:", err));

// Define a schema and model
const itemSchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: String,
  createdAt: { type: Date, default: Date.now }
});

const ItemModel = mongoose.model('Item', itemSchema);

Dynamic CRUD Operations

Create an Item (POST)

To create an item using data from a POST request sent by Angular:

app.post('/items', (req, res) => {
  const newItem = new ItemModel({
    name: req.body.name,
    description: req.body.description
  });

  newItem.save()
    .then(item => res.status(201).send(item))
    .catch(err => res.status(400).send(err));
});

Read Items (GET)

To get all items:

app.get('/items', (req, res) => {
  ItemModel.find()
    .then(items => res.status(200).send(items))
    .catch(err => res.status(500).send(err));
});

To get a single item by ID:

app.get('/items/:id', (req, res) => {
  ItemModel.findById(req.params.id)
    .then(item => {
      if (!item) res.status(404).send('Item not found');
      else res.status(200).send(item);
    })
    .catch(err => res.status(500).send(err));
});

Update an Item (PUT)

To update an item by ID:

app.put('/items/:id', (req, res) => {
  ItemModel.findByIdAndUpdate(req.params.id, req.body, { new: true })
    .then(item => res.status(200).send(item))
    .catch(err => res.status(400).send(err));
});

Delete an Item (DELETE)

To delete an item by ID:

app.delete('/items/:id', (req, res) => {
  ItemModel.findByIdAndRemove(req.params.id)
    .then(item => res.status(200).send({ message: 'Item deleted successfully' }))
    .catch(err => res.status(500).send(err));
});

Finalizing Your Setup

After defining your routes, ensure you start the Express server:

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

This setup allows your Angular application to dynamically interact with your Express backend, performing CRUD operations by sending and receiving JSON data.

Bringing It All Together: CRUD on the Frontend with Angular

Integrating Angular with a backend API involves creating services to handle API requests, models to represent data, components to interact with the user, and forms for CRUD operations. Below, I’ll guide you through setting up a simple Angular application that interacts with the Express.js API we set up for managing items.

Step 1: Setting Up Angular Environment

First, ensure you have Angular CLI installed. If not, install it via npm:

npm install -g @angular/cli

Create a new Angular project:

ng new angular-items-app

Navigate into your project directory:

cd angular-items-app

Step 2: Creating an Item Model

Generate an Item model to represent the data structure:

ng generate class models/item --type=model

Edit src/app/models/item.model.ts:

export class Item {
  _id?: string;
  name: string;
  description?: string;
  createdAt?: Date;
  
  constructor(name: string, description: string) {
    this.name = name;
    this.description = description;
  }
}

Step 3: Creating a Service to Interact with the API

Generate a service for API interactions:

ng generate service services/item

Edit src/app/services/item.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Item } from '../models/item.model';

@Injectable({
  providedIn: 'root'
})
export class ItemService {
  private apiUrl = 'http://localhost:3000/items'; // Adjust if your API endpoint differs

  constructor(private http: HttpClient) { }

  getItems(): Observable<Item[]> {
    return this.http.get<Item[]>(this.apiUrl);
  }

  getItemById(id: string): Observable<Item> {
    return this.http.get<Item>(`${this.apiUrl}/${id}`);
  }

  createItem(item: Item): Observable<Item> {
    return this.http.post<Item>(this.apiUrl, item);
  }

  updateItem(id: string, item: Item): Observable<Item> {
    return this.http.put<Item>(`${this.apiUrl}/${id}`, item);
  }

  deleteItem(id: string): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}

Step 4: Creating Components for CRUD Operations

List Items Component

Generate a component to list items:

ng generate component components/item-list

Edit src/app/components/item-list/item-list.component.ts:

import { Component, OnInit } from '@angular/core';
import { ItemService } from '../../services/item.service';
import { Item } from '../../models/item.model';

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {
  items: Item[] = [];

  constructor(private itemService: ItemService) { }

  ngOnInit(): void {
    this.itemService.getItems().subscribe(items => {
      this.items = items;
    });
  }
}

And in src/app/components/item-list/item-list.component.html, display the items:

<ul>
  <li *ngFor="let item of items">{{ item.name }}: {{ item.description }}</li>
</ul>

Create Item Component

For brevity, I’ll guide you through setting up one more component: the one for creating items. For updating and deleting, you’d follow a similar pattern.

Generate a component:

ng generate component components/create-item

Edit src/app/components/create-item/create-item.component.ts:

import { Component } from '@angular/core';
import { ItemService } from '../../services/item.service';
import { Item } from '../../models/item.model';

@Component({
  selector: 'app-create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css']
})
export class CreateItemComponent {
  item: Item = new Item('', '');

  constructor(private itemService: ItemService) { }

  addItem(): void {
    this.itemService.createItem(this.item).subscribe(result => {
      console.log(result);
      this.item = new Item('', ''); // Reset for next input
    });
  }
}

And in src/app/components/create-item/create-item.component.html, create a simple form:

<div>
  <input [(ngModel)]="item.name" placeholder="Name" name="name">
  <input [(ngModel)]="item.description" placeholder="Description" name="description">
  <button (click)="addItem()">Add Item</button>
</div>

Step 5: Updating AppModule

Ensure your AppModule (found in src/app/app.module.ts) imports FormsModule, HttpClientModule, and declares the components we’ve created. Also, for ngModel to work, you must import FormsModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ItemListComponent } from './components/item-list/item-list.component';
import { CreateItemComponent } from './components/create-item/create-item.component';
// Import other components

@NgModule({
  declarations: [
    AppComponent,
    ItemListComponent,
    CreateItemComponent
    // Other components
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

By following these steps, you’ve set up a basic Angular application capable of performing CRUD operations on your Express.js backend. This involves creating models to represent your data, services to interact with the API, and components to handle user input and display data.

Conclusion

We’ve explored the basic aspects of building MEAN Stack applications, from setting up a development environment and understanding core technologies like SQL DB, Express.js, Mongo, and Node.js in this comprehensive guide. Each step is designed to provide you with the practical knowledge necessary for creating dynamic, scalable web applications using this powerful technology set.

For additional support and resources, the developer community offers a wealth of information. For MongoDB, Express.js, Angular, and Node.js, websites such as Stack Overflow, GitHub, and official documentation are invaluable.

If your project needs expert guidance or if you’re looking to hire nodejs developers, consider WireFuture as your nodejs development partner. With a team of experienced professionals who specialize in the MEAN Stack, WireFuture is committed to transforming your ideas into robust, market-ready solutions. Whether you’re starting a new project or looking to enhance an existing application, WireFuture offers the expertise and support to help you achieve your development goals.

Share

clutch profile designrush wirefuture profile goodfirms wirefuture profile
Join the Digital Revolution with WireFuture! 🌟

Step into the future with WireFuture at your side. Our developers harness the latest technologies to deliver solutions that are agile, robust, and ready to make an impact in the digital world.

Hire Now

Categories
.NET Development Angular Development JavaScript Development KnockoutJS Development NodeJS Development PHP Development Python Development React Development Software Development SQL Server Development VueJS Development All
About Author
wirefuture - founder

Tapesh Mehta

verified Verified
Expert in Software Development

Tapesh Mehta is a seasoned tech worker who has been making apps for the web, mobile devices, and desktop for over 13+ years. Tapesh knows a lot of different computer languages and frameworks. For robust web solutions, he is an expert in Asp.Net, PHP, and Python. He is also very good at making hybrid mobile apps, which use Ionic, Xamarin, and Flutter to make cross-platform user experiences that work well together. In addition, Tapesh has a lot of experience making complex desktop apps with WPF, which shows how flexible and creative he is when it comes to making software. His work is marked by a constant desire to learn and change.

Get in Touch
Your Ideas, Our Strategy – Let's Connect.

No commitment required. Whether you’re a charity, business, start-up or you just have an idea – we’re happy to talk through your project.

Embrace a worry-free experience as we proactively update, secure, and optimize your software, enabling you to focus on what matters most – driving innovation and achieving your business goals.

Hire Your A-Team Here to Unlock Potential & Drive Results
You can send an email to contact@wirefuture.com
clutch wirefuture profile designrush wirefuture profile goodfirms wirefuture profile good firms award-4 award-5 award-6