Mean stack tutorial in 30 minutes-2020

by Priyanka Arora
Jun 7, 2020
Mean stack tutorial in 30 minutes-2020

The simplest MEAN Stack Tutorial on Web you would found. MEAN stack is trending since 2015 and it is not slowing down anytime soon. MEAN  stands for MongoDB, Express Js, Angular, and NodeJS. This tutorial is for developers who have not even worked with any of this one too. SO, relax this is not going to disappoint and leave you hanging in between. We promise♥. In this tutorial, we will build a NodeJs Express Server where we are using express routing, body-parser to handle requests from angular application, that establish a connection with MongoDB database. We will be building a separate application for Angular. SO, we have two applications here. Don’t worry, it is still simple. We will be doing basic get and post from application to the server and be interacting with the database. SO, not complicating with authentication and stuff. Keeping it simplest possible. So, let’s get coding now.

Setting Up NodeJS Express Server Application

Here we are building the simplest NodeJs Express Server Possible in this MEAN Stack tutorial. Routing would be via Express default routing. For parsing the requests we would be using  body-parser for the incoming request. And establish connection with MongoDB using Mongoclient. The prerequisites remain that you have nodejs and npm installed in the system. Under A folder, use npm init to package json. The server is being configured for port 3000 here and all the code is kept at app.js only. So, to run use node app.js command. And then on browser type localhost:3000

Install the following dependencies:

npm install express

npm install body-parser

npm install mongodb –save

Add the code in app.js

var express=require('express');
var app=express();
	;bodyParser = require('body-parser');
const MongoClient = 
const uri = "mongodb+srv://<
const client 
	= new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology:
	({ extended: true }));
app.all("/*", function
	(req, res, next){
 res.header('Access-Control-Allow-Origin', '*');
 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');

	 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
	 Content-Type, Accept");
	 'Content-Type, Authorization, Content-Length, X-Requested-With');
	client.connect(err => {
 const collection = client.db('EngineerDiariesDB').
	var object={id:3,username:req.body.username}
	function(err, res) { 
 if (err) console.log(err) ;
 console.log("1 record inserted"); 
 client.connect(err => 
 const collection = client.db('EngineerDiariesDB').collection('Profile');
 collection.find({}).toArray(function(err, result) {
 if (err) console.log(err);
var server=app.listen(3000,function() {});


uri contains the mongodb connection string . app.all() contains headers to enable cors as the request would be from the angular application server. There are two routes (/insert) that would insert the req.body into the MongoDB and /select to return the collection array of documents. EngineerdiariesDB is the database name here and Profile is the name of the collection. Again the nodejs server is hosted at port 3000. to ensure that you have established connection with DB we have logged Connected message in the console. Congratulations you have completed the first part of the Mean stack tutorial. Now, we will create an angular application that will send a request to this server.

Setting Up Angular Application

As discussed above we would be creating a separate application for angular. Under angular folder run ng new angularappThis will take a few minutes to set up and say yes to the routing part. Move into the directory using cd .\angularapp\ .  Next, we will create a signup component using ng g c signup and to run the angular server use command ng serve –oSo, you now have an angular application at port 4200 set up.

Add default route to signup component 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SignupComponent } from './signup/signup.component';
const routes: Routes = [];
  imports: [RouterModule.forRoot(
    [{path: ', component: SignupComponent}])],
 exports: [RouterModule]
export class AppRoutingModule {

Create a user model

create a class named user.ts where we need only 1 parameter username and add the following code to it.

export class user

Add the following modules in app.module.ts

Here we have added FormsModule for two way binding and httpclient to establish connection with the server

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SignupComponent } from './signup/signup.component'
import {HttpClientModule} from '@angular/common/http';

  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Comment index.html

By default, they have added logo and text which we don’t require. So, better to comment that out.

<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <base href="/">

Add following code to signup.html

Here we have created a basic form which binds usrname to the user1 object via two-way binding and on submit button calls formSubmit() and below list out the username and id when called on init() as in .ts code will look below.

        <h1>Signup Form.</h1>
        <form >
            <label >Name:</label>
            <input name="username" id="username" [(ngModel)]="user1.username" #username="ngModel" type="text"/>
            <input type="button" value="Submit" (click)="formSubmit(user1.username)"/>
        <h1>List of Username:</h1>
        <ul *ngFor="let item of data;index as i;">

Add following code to signup.ts

Here we have declared user1 object. Onit() we call  viewData() to get the objects via httprequest to select endpoint. and on formSubmit() we insert the data using /insert endpoint. Replace the ipaddress though and we have successfully completed step 2 of this mean stack tutorial.

import { Component, OnInit } from '@angular/core';
import { user } from '../user';
import { HttpClient, HttpHeaders } from '@angular/common/http';
  selector: 'app-signup',
  styleUrls: ['./signup.component.css']
export class SignupComponent implements OnInit {
  constructor(private http: HttpClient) 
 this.user1=new user();  
 formSubmit( username:string)
  const headers = new HttpHeaders()       
    .set('Authorization', 'my-auth-token')     
    .set('Content-Type', 'application/json');'http://ipaddress:3000/insert', JSON.stringify(this.user1), {    
   headers: headers     })     
 .subscribe(data => {       console.log(data);     });   
   const headers = new HttpHeaders()  
   .set('Authorization', 'my-auth-token')   
   .set('Content-Type', 'application/json');'http://ipaddress:3000/select',JSON.stringify(this.user1),{ headers: headers}) 
 .subscribe(data => { 
 console.log(data);; });
Mean stack tutorial in 30 minutes-2020
Mean stack tutorial in 30 minutes-2020
And we have successfully completed this mean stack tutorial. And you deserve a party because not a lot of people exactly know-how the full stack works also. 🤓🤓

Frequently Asked Questions

React is more suitable where components needs to be refreshed over and over whereas angular is a framework for bigger applications

Should know both but mastering one is enough. So, you enjoy UI or queries more?

Yes. Use libraries for mysql instead on mongodb

Well lets just say MEAN will stay!

Similar Posts

Express Js Routing Tutorial | Beginners
Jun 7, 2020, 1649 Views, 2
Mysql with NodeJs Connection and CRUD
Jun 7, 2020, 1649 Views, 2
Sql Server with NodeJs CRUD Operations
Jun 7, 2020, 1649 Views, 2
MongoDB with NodeJs CRUD Tutorial Guide
Jun 7, 2020, 1649 Views, 2

Comments Section

Jun 15, 2021


Nov 11, 2020

Worked like a charm!