Skip to content

Understanding the MEAN Stack: A Deep Dive with Examples

Hi there! As a full-stack developer who uses JavaScript daily, I wanted to provide you with a solid guide on the MEAN stack. I‘ll explain what each component technology does, how they fit together, and even walk you through building a web app yourself.

Whether you‘re considering MEAN for your next project or just a curious technologist (like me!), you‘ll have a crystal clear understanding by the time you reach the end. Sound good? Let‘s get started!

What Exactly Is the MEAN Stack?

The acronym MEAN stands for MongoDB, ExpressJS, AngularJS, and Node.js. Together, these four technologies provide an end-to-end JavaScript-based solution for building fast, scalable web applications.

MongoDB brings the database – specifically a document-oriented NoSQL database that stores flexible JSON data.

ExpressJS is a server-side web application framework that runs on top of Node.js to make backend development and API routing simpler.

AngularJS (also just called Angular) powers the frontend, providing a modular JavaScript framework for building user interfaces and client-side logic.

Node.js wraps everything together – it‘s a JavaScript runtime environment that lets developers write server-side code opposed to just running JS in the browser.

So in summary, the MEAN stack uses JavaScript across the full application: MongoDB to persist and query data, Express + Node for the backend and API server, and Angular on the frontend. This consistent language and tightly integrated stack makes building complex, scalable web apps much faster and simpler to maintain.

A Brief History Behind the MEAN Stack

Let‘s rewind a bit to understand the origins of the MEAN stack. As a developer who enjoys using all four technologies, I wanted to highlight the history so you can appreciate how we arrived at the MEAN concept.

MongoDB – Developed by the company MongoDB Inc. and first released in 2009. Its flexible data schema was built to handle modern web app requirements better than rigid SQL databases.

ExpressJS – Initial public release in November 2010 by TJ Holowaychuk. Offered server-side logic framework for Node.js instead of reinventing the wheel.

AngularJS – Created in 2009 internally by Google for their apps. Went open source in 2010. Simplified building complex frontend SPAs using MVC patterns.

Node.js – Engineered by Ryan Dahl in 2009. Allowed running JavaScript server-side by leveraging Chrome‘s high performance V8 engine.

Around 2010, Node.js brought the ability to run JS outside the browser. Meanwhile, MongoDB provided ways to store data and ExpressJS + AngularJS handled server-side and client-side app development.

The potential synergy was clear. By 2012 when the term "MEAN stack" emerged, developers combined these technologies to create full-stack JS web apps. The rest is history!

Why Each Component of the MEAN Stack Matters

Now you know the pieces of MEAN, but why does each technology matter? Let me provide some developer context about their standout features and value they brought to web engineering:

MongoDB

MongoDB shattered assumptions that data storage always required rigid schemas and SQL language compliance. Their document model instead stores records as BSON documents – JSON-like structures with dynamic schemas.

This means developers can represent data naturally without migrations for schema changes down the road. MongoDB also scales horizontally with automatic sharding across replicas. Overall, it provided the persistence layer needed to manage data in modern web applications.

ExpressJS

As Node.js grew in popularity for server-side JS, developers needed a web application framework to simplify common tasks like routing URLs to handlers. Enter ExpressJS – it saved developers from reinventing by providing utilities out-of-the-box like:

  • Routing HTTP requests
  • Integrating with view rendering engines
  • Adding middleware for requests/responses
  • Simplifying error handling

Combined with Node, ExpressJS made writing the backend for web apps extremely productive. It has since become the standard server-side framework for Node development.

AngularJS

While developers used JavaScript in the browser for years before AngularJS, the code for non-trivial apps ended up disorganized and messy. Angular organized client-side code using Model View Controller architecture:

  • Models – data objects
  • Views – UI templates
  • Controllers – JS code behind views

This matched common server-side MVC frameworks but for browser JS. Additionally, AngularJS utilizes two-way data binding which connects UI elements directly to data models. The net result – building web UIs became simple and fast.

Node.js

Node.js brought JavaScript to the server environment. Frontend developers could finally use their existing JS skills to code the backend. Node did this by providing features like:

  • Asynchronous (non-blocking) APIs
  • Event-driven architecture
  • Lightweight HTTP server framework

Combined with its ultra-fast Google V8 execution, Node.js enabled real-time web applications not previously possible. The meteoric rise of Node and Express for server-side JS is a testament to its impact.

Hopefully by covering what each component brings to the table individually, you now appreciate why together they make the MEAN stack so useful!

Building a To-Do Application with MEAN

Enough background and terminology – let‘s look at some code! I‘ll walk you through a simple MEAN application implementing a To-Do list. Follow along by building it yourself or just reference to understand how the moving pieces fit together.

Here is an outline of steps we‘ll cover:

  1. Initialize Node.js project
  2. Install ExpressJS and MongoDB packages
  3. Set up Express server
  4. Connect MongoDB database
  5. Create AngularJS frontend
  • Controller
  • View template
  1. Build Node/Express API
  • GET todos
  • POST add todo
  1. Connect frontend and backend

Let‘s get going!

Steps 1-2: Initialize Project and Install Packages

Use NPM to initialize a new Node project. This creates a package.json to track dependencies:

$ npm init -y  

Next install Express and the MongoDB client:

$ npm install express mongodb

Verify they now appear in your package.json file before proceeding.

Step 3: Configuring the Express Server

In the root of your project, create a server.js file and add the following:

const express = require(‘express‘);

const app = express();

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

app.listen(3000, () => {    
  console.log(‘Server running on http://localhost:3000‘);
});

This basic Express server responds to all HTTP GET requests at route / with the text "Hello World". The app.listen call starts up the server on port 3000.

Step 4: Connecting to MongoDB

Now let‘s integrate a MongoDB database using MongoDB Node.js driver. We will call our database mean-example and store TODO data in a todos collection.

Underneath the other Express code in server.js, add this block to connect MongoDB:

const MongoClient = require(‘mongodb‘).MongoClient;
const dbName = ‘mean-example‘; 

MongoClient.connect(`mongodb://localhost:27017/${dbName}`, {
  useNewUrlParser: true     
}).then(client => {

    console.log(‘Connected to Database‘)

    const db = client.db(dbName)
    const todosCollection = db.collection(‘todos‘)

    // API route handlers go here

}).catch(err => console.error(err))

MongoDB will now connect on startup before our Express server begins receiving requests. Our Node code can access the todosCollection object to execute CRUD operations from API routes.

Step 5: Building the AngularJS Frontend

Let‘s temporarily switch gears to the frontend. We‘ll need a simple Angular app configured to display TODO data.

Inside the project root, create a folder called public. Then add an index.html file with the barebones Angular setup:

<!DOCTYPE html>
<html ng-app="todoApp">

  <head>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

      <script>

        angular.module(‘todoApp‘, []);

      </script>

  </head>

  <body>



    <div ng-controller="TodoController">

      {{ message }}

    </div>

  </body>

</html>

This markup sets up the Angular app todoApp and a basic controller. Later we‘ll flesh out the UI and logic.

Step 6: Creating REST API Routes

Now let‘s enable some API endpoints with Express and MongoDB to perform CRUD operations on TODO data.

Back in server.js, add two route handlers:

// GET /api/todos
app.get(‘/api/todos‘, async (req, res) => {

    const todos = await todosCollection.find().toArray();

    res.status(200).json(todos);

});

// POST /api/todos 
app.post(‘/api/todos‘, async (req, res) => {

    const newTodo = req.body;

    const result = await todosCollection.insertOne(newTodo);

    res.status(201).json(result);

});

These two routes fetch and add TODO records by interacting with our MongoDB collection.

Step 7: Connecting Frontend to Backend

Finally, enable serving static files from Express so it can access the Angular frontend:

app.use(‘/‘, express.static(__dirname + ‘/public‘));

Also update the Angular controller:

angular.module(‘todoApp‘, [])
.controller(‘TodoController‘, function($scope) {

    $scope.message = ‘My Todos‘;

});

Now visit http://localhost:3000. You should see your Angular app with the message rendering!

And there you have it – a basic MEAN application with a frontend connected to backend API routes. Congrats on following along! 🎉

Comparing MEAN to Other Stacks

The MEAN stack provides a clearly effective way to build full web applications. But how does it compare to alternatives like LAMP (Linux, Apache, MySQL, PHP) or MERN (swaps Angular for React)?

Based on my experience, here is how MEAN typically stacks up:

Performance – By using JavaScript across frontend and backend, MEAN apps avoid context switching between languages. Node + Express also enables very high throughput APIs.

Flexibility – MongoDB schemaless models and modular Angular UIs handle new requirements as you scale.

Maintainability – Less code and consolidation to JS smooths onboarding across engineering teams.

Modern Capabilities – MEAN unlocks real-time, reactive web capabilities suited to the processing needs of modern apps.

The downsides relate primarily to code complexity – with everything in one language, troubleshooting bugs can be challenging during initial development.

However, with clean separation of concerns between Angular, Express, and MongoDB, apps with sound architecture avoid this downfall. Overall MEAN‘s strengths in the modern web landscape typically outweigh the growing pains.

Keep Learning!

Congratulations, you made it to the end of our epic MEAN stack overview! You now should have a solid high-level grasp. For even deeper knowledge, check out these resources:

Thanks for sticking with me on this JavaScript full stack adventure! Whether you‘re just exploring or learning to amp up your web development skills, I hope you‘ve gained insights into just how useful the MEAN approach can be.

Now go out and build something awesome 🚀