MEAN Stack Quick Guide.

Guide to become a Full Stack developer using M.E.A.N

Onejohi
11 min readNov 16, 2018

--

If you’re new to web development you’ve probably heard of the MEAN stack and have been wondering what it means. MEAN is an abbreviation for Mongo, Express, Angular and NodeJS. I really don’t understand why Express and NodeJS represented as two separate entities but in reality, they’re one of the same thing since Express is a NodeJS library for creating servers. It’s almost like saying Angular and JavaScript. So, now we’re limited to three entities, Mongo, Express(NodeJS) and Angular. Let’s discuss each’s role in full stack development.

To create a system, you require a UI for users to interact with a set of data. To interact with this data, users have to use an interface to interact with the data as if given free access to the database users will wreak havoc. The interface between the user’s UI and the data in the database is what is called an API (Application Programming Interface). So, Angular is what is used to build the UI. Angular displays data to the user in an organized manner and users can then interact with data by pressing buttons, entering fields and tapping on items. The API is made using NodeJS (Express framework), the API receives requests through endpoints like /users/getusers or /profile/update and runs custom scripts to get data, update data or delete data from the database. The API is what is also called the server since it’s role is to respond to requests and mostly serve data to clients. A server is both the hardware and the software running on a host computer. Finally, the database is MongoDB which is a schemaless database that is gaining a lot of popularity. You can still use MySQL instead of MongoDB if that’s what you’re used to or any other DB for that matter.

Looking at the MEAN Stack, it’s just a combination of preferences to how you can build full stack applications. You can use MySQL, Cassandra, PostgreSQL, SQLite or MS SQL in place on Mongo, you use Ember, Flask, Django, Falcon, C# WebAPIs, Spring or PHP in place of Express(NodeJS) and you can also use ReactJS, Vue, Polymer or Ionic in place of Angular. The MEAN stack is simply a combination of the most popular frameworks and technologies.

Let’s get started.

To get started, we’ll start by exploring the front end which is built in Angular. You’ll have to install the @angular/cli to play around with angular, and the angular/cli is intalled via npm which comes bundled with node. To download NodeJS, head over to https://nodejs.org and download the latest stable version of NodeJS. After installing NodeJS, you’ll have to restart all your open terminals (cmd) so that they can pick up node as an environment variable pointing to your installation of NodeJS. NodeJS is packed with a repl environment. The REPL (read eval print loop) environment reads user inputs (expressions in JS), evaluates them and returns the results to the user via the terminal. REPL is launched when you enter node on your terminal.

meAn (Angular section)

Installing the Angular CLI.

To install @angular/cli, you’ll need to use npm which comes bundled with NodeJS on installation. This example works for Angular 2–7 as at the time of writing this article the latest version of Angular was 7.

npm install -g @angular/cli

When installing packages via npm install command, using -g flag installs the package globally. When your package is globally installed, it’s accessible in the computer environment similar to NodeJS. For Angular, the CLI is available using ng .

ng --help

When you type in the following command after installing the Angular CLI, you’ll see a long list of commands you can use to configure your Angular application. The most common ones you’ll use are ng new , ng build , ng generate and ng serve . To create a new Angular application, use the following command.

ng new MyApp

This will create a new Angular app called MyApp and install the modules required to run a basic Angular application in the node_modules folder. To reduce redundancy, I’ll let you learn Angular from a previous tutorial I had earlier made if you’d like to. You can choose to skip this section since a basic Angular app will work as well, you don’t have to change it.

Once done with the basics, you can check out a cheat sheet I made for you to familiarize yourself with Angular.

From angular 2–7, the syntax doesn’t change much. You can comfortably use your Angular 2 knowledge to build an Angular 7 app.

If you’re from a React background or any other library that’s not Angular, the ng build command is similar to how you’d build your application for production using other libraries or frameworks. For Angular, the files created are inline.js bundle.js index.html etc. The index.html is your SPA (Single Page Application). This means your entire Angular app is loaded once your index.html is called. What happens is the application is actually contained in your vendor.js inline.js files and these files manipulate your DOM to change elements just as you would with Vanilla JS. The explanation is Angular is a framework that makes it easier to build apps with features that Angular makes available like interpolation, two-way data binding etc. In other words, your Angular app builds into plain JS which can then be executed by the browser.

What I found confusing to most developers is routing. What you ought to know is Angular doesn’t do server-side routing, so you can have a route on your server that is /users/profile and a route in your Angular application /users/profile and they would both work. When you go to your browser and request for http://host:port/users/profile the route on the server of your application will respond and not your Angular application. This is because Angular kind of simulates routing but actually doesn’t “route”. If you create your angular app using the command ng new MyApp --routing you’ll see an app.routing.ts file. This file is where you create Angular routes, the trick is in the template, when you open app.component.html you’ll notice a new element <router-outlet></router-outlet> . This is the element used by Angular to simulate routing. Anything outside the router-outlet will appear on all your Angular pages. So if you want a persistent toolbar, add it outside your router-outlet. Think of the router-outlet as a switch template where Angular checks the route using routerLink='/users/profile' and matches a case that satisfies the route in the app.routing.ts file and displays the template over the router-outlet element. This is how I can best explain Angular simulates routes that are only accessible via routerLink and the server API endpoints remain the actual routes you can visit directly using your browser.

So in essence, Angular is just one HTML document, whenever you navigate to different pages of your Angular app, Angular simply switches components via the routerModule to make it seem as if you’re browsing different pages while in reality, you’re browsing components that fill the entire window or leave out a fixed persistent navbar at the top… Pretty smart, right? 😉

mEaN (Express and NodeJS section)

Let’s now create our NodeJS server.

There are a couple of ways to do this, let’s start with the simplest and install the package express generator.

>npm install -g express-generator

Note that you ought to install it globally. Express generator generates an express application template that’s basic enough to get you started with two basic routes, / and /users . To create a new express app using the template, use the command express appname where appname is a custom name for your app.

You’ll notice in the package.json file, there are a list of dependencies together with express and you might go like, “What’s all this? Shouldn’t it be express only?”. Well, yes but those extra dependencies help a lot like body-parser helps you parse the request content and headers, jade which was renamed to pug is a templating engine and cookie-parser does what you think it does, help parse cookies.

Instead of all this junk, you can create a bare minimum application of an express app from scratch that will serve your built Angular app’s index.html file.

Start by installing express.

npm install express --save

then copy the following code to app.js or index.js file.

let express = require('express')
let path = require('path')
let app = express()
//configure app to serve static files from public folder
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', (req, res, next) => {
//respond with index.html
req.sendFile('index.html')
})
app.listen(3000 || process.env.PORT, () => {
console.log("Server listening on port 3000)
})

That’s totally it. What this does is configure your express app to serve static files (your Angular app) from a folder called public using the express.static() method, but then I join __dirname and public. __dirname is a global object that returns the current directory name where your app is currently running. Create a new folder in the root of your app(where your app.js or index.js resides) and call it ‘public’ or whatever you would wish. The app on receiving a GET request on http://127.0.0.1:3000 will respond with your app. Dump all the content from the dist folder of your Angular app after building it into your express app public folder.

If you’d wish to learn more about express, check out a previous article I did that would take you through smoothly to getting started.

Now that we’ve built our frontend and backend, lemme show you how to save data persistently to a database which in our case is MongoDB.

Mean (MongoDB)

Getting started with MongoDB.

MongoDB is a schemaless non-relational database that stores data in a JavaScript friendly format known as BJSON.

BSON is a computer data interchange format used mainly as a data storage and network transfer format in the MongoDB database. It is a binary form for representing simple data structures, associative arrays, and various data types of specific interest to MongoDB

Wikipedia.

Let’s compare how the same object is stored in a JSON file vs in MongoDB.

{
"name": "John Doe",
"marks": [56,67,67,5],
"teachers": [
{ "name": "Karen", "class": "Math" },
{ "name": "Ali", "class": "History" }
]
}

The same data in MongoDB would appear like this.

{
_id: ObjectId("5ab25d03df4c9f1520b3b6b4"),
name: "John Doe",
marks: [56,67,67,5],
teachers: [
{ name: "Karen", class: "Math" },
{ name: "Ali", class: "History" }
]
}

The only thing that changes is Mongo has an _id of type ObjectId which is a unique id for each object similar to a primary key in SQL but in Mongo, there are a number of factors included to generate a unique id which includes the timestamp as well.

To learn more about MongoDB check out this awesome article by Vanessa Ating

and if you’re on a Mac, check out Martin Lasek’s article.

Mongoose.

When interacting with a Mongo database, the best tool to use in NodeJS is Mongoose. Mongoose lets you define schemas and models for your data, and use the schema to execute common Mongo methods like find() findOne etc.

Installing Mongoose is fairly easy, a simple

npm install mongoose body-parser --save

would suffice. Note body-parser is optional but you might want to install it to save you a lot of hustle when trying to parse data from requests. This time instead of -g flag for global installation, we’ll do --save instead to save the packages as dependencies in your package.json. The package.json helps your app install dependencies it would require when migrated to another folder. Normally, node_modules folder isn’t transferred as that would be redundant. The solution is to save dependencies on your package.json, then whenever you transfer your projects, simply do npm install to reinstall all your dependencies into the new folder.

We will use the data in the example above to show how to save and get data from our MongoDB instance. We’ll start by creating a models folder where we’ll add our Mongoose Schemas. Let’s create a student.js file for our student schema inside our models folder.

let mongoose = require('mongoose')
let studentSchema = mongoose.Schema({
name: String,
marks: Number[],
teachers: {
name: String,
class: String
}
}, { collection: 'students' })
let Student = mongoose.model('Student', studentSchema)
module.exports = Student

This creates a model of Student that has a defined schema and will be stored in a collection called ‘students’ in your MongoDB instance. The command for creating this collection after installing Mongo is db.createCollection('collectionname')

Let’s modify our app.js file to now look like this.

You can now add as many users as you like by creating a form on your angular app that sends data to your endpoints. One thing to note while testing is you might want to implement cross-origin requests which are restricted by default. A simple way to do this is install a package called Cors from npm npm install cors --save and add the following like to configure your app.

app.use(cors())

Simple and straightforward, now you’ll be able to serve your Angular app on port 4200 when developing and test your API endpoints on port 3000 without errors.

If you still can’t wrap your head around how the front end and backend work, check out this article I did that might help you out a little.

Now you’re on your way to becoming a full stack developer after understanding the basics of how to come up with the simplest form of a full stack MEAN application. I would advise you to learn the basics that are required for each technology to avoid frustrating moments that I’ve witnessed new devs going through because of simply not learning the basics first. To learn Angular, please make sure you have a good understanding of JavaScript (not basic but good), basic understand of TypeScript, HTML, CSS and a little bit of SCSS though the last is optional. To learn Express you need a very solid understanding of NodeJS and JavaScript. To learn MongoDB you need a solid understanding of JSON, and JavaScript data types. Even though you commonly hear JS has no types, I’m talking of objects, arrays, undefined, nulls, strings and numbers and methods that you can use to manipulate them. The reason I insist on this is I’ve had a dev who wanted me to help him iterate over an object as though it was an array and use *ngFor in Angular to display the data. Despite numerous attempts, he still couldn’t understand why he couldn’t use ngFor to iterate over his object as shown in some example simply because he didn’t understand basic JavaScript before jumping over to Angular.

This is the only way you’ll have it easy with MEAN, skip one and you’ll be doomed for disaster. Trust me, I’ve seen it, not once. 😜

Thank you for going through this article, don’t forget to follow and share if you find it useful. 😃

--

--

Onejohi

Creative 🚀 | Gamer 🎮 | Web & App developer 💻📱 | Graphics Designer 📏📝 | Entrepreneur 💶 | Cool AF 😎🤓 https://onejohi.com | WhatsApp +254727321766