Mean Stack Angular Crud Application Tutorial

Sunday, January 5, 2020

Mean Stack Angular Crud Application Tutorial


The term MEAN stack refers to a collection of JavaScript-based technologies used to build web applications. MEAN stands for MongoDB, Express.js, Angular, and Node.js.

MEAN stack application - MongoDB, Express, Angular, Node.js
MEAN Stack Application

The below topics are covered in this blog -

1) Overview of the MEAN stack
2) What does CRUD stand for?
3) Architecture of the MEAN stack application
4) Building the Node.js backend
5) Building the Angular frontend

1. Overview of the MEAN Stack

MongoDB — MongoDB is a schema-less NoSQL database. It stores data in a binary JSON (BSON) format, which makes it easy to pass data between client and server. If you haven't seen my MongoDB tutorial yet, see my related post: Complete Guide to MongoDB.

Angular — Angular is a JavaScript framework developed by Google. It provides features like two-way binding, routing, sharing data between components, RxJS, and observables. In short, it is a complete solution for rapid frontend development.

Node.js — Node.js is a server-side JavaScript execution environment built on Google Chrome's V8 runtime. It helps you build highly scalable, concurrent applications quickly. See my related post: Complete Guide to Build a RESTful API with Node.js.

Express.js — Express is a lightweight framework for building web applications in Node.js. It provides a robust set of features for single- and multi-page apps and was inspired by the Ruby framework Sinatra. We use Express in Node.js as our web application framework.

2. What Does CRUD Stand For?

CRUD stands for Create, Read, Update, and Delete — the four basic operations of persistent storage.

CRUD stands for Create, Read, Update, Delete
CRUD Stands For

We are going to build an application that performs all four operations using the MEAN stack.

3. Architecture of the MEAN Stack Application

The diagram below shows the architecture of the application we are building. The frontend uses Angular, and every user interaction — create, read, update, delete — goes through Node.js.

MEAN stack application architecture with Angular, Node.js and MongoDB
MEAN Stack Application Architecture

Node.js acts as the mediator that talks to the MongoDB database and returns data to the frontend.

4. Building the Node.js Backend

Step 1 — Generate a package.json. Create a folder, then run:

mkdir meanstack_backend
cd meanstack_backend
npm init          # press enter through the prompts
npm install body-parser cors express mongoose nodemon --save

Step 2 — Create the entry file, index.js:

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

const mongoose = require('./db.js');
const personController = require('./controllers/personController.js');

var app = express();
app.use(bodyParser.json());
app.use(cors({ origin: 'http://localhost:4200' }));

// Application testing API
app.get('/app/testing', (req, res) => {
  res.send({
    "message": "App is working fine",
    "status": 200
  });
});

app.use('/person', personController);

app.listen(3000, () => console.log('Server connected to port: 3000'));

db.js — the database connection:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/firstdb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err) => {
  if (!err) {
    console.log('MongoDB connected ....');
  } else {
    console.log('Error in DB connection: ' + JSON.stringify(err, undefined, 2));
  }
});

module.exports = mongoose;

model/person.js — the data model:

const mongoose = require('mongoose');

var Person = mongoose.model('Person', {
  name:  { type: String },
  mail:  { type: String },
  class: { type: Number }
});

module.exports = { Person };

controllers/personController.js — the CRUD routes:

const express = require('express');
var router = express.Router();

var { Person } = require('../model/person.js');
var ObjectId = require('mongoose').Types.ObjectId;

// Get all users
router.get('/', (req, res) => {
  Person.find((err, doc) => {
    if (!err) { res.send(doc); }
    else { console.log('Error retrieving persons: ' + JSON.stringify(err, undefined, 2)); }
  });
});

// Insert a user
router.post('/', (req, res) => {
  var per = new Person({
    name:  req.body.name,
    mail:  req.body.mail,
    class: req.body.class
  });

  Person.findOne({ 'mail': req.body.mail }, (err, docs) => {
    if (!docs) {
      per.save((err, doc) => {
        if (!err) {
          res.status(200).send({ auth: true, doc, message: '1 document inserted' });
        } else {
          console.log('Error inserting data: ' + JSON.stringify(err, undefined, 2));
        }
      });
    } else {
      console.log('User already exists: ' + req.body.mail);
      res.status(400).send({ message: 'User already exists: ' + req.body.mail });
    }
  });
});

// Update a user
router.put('/:id', (req, res) => {
  if (!ObjectId.isValid(req.params.id))
    return res.status(400).send(`No record with given id: ${req.params.id}`);

  var per = {
    $set: {
      name:  req.body.name,
      mail:  req.body.mail,
      class: req.body.class
    }
  };

  Person.findOneAndUpdate({ mail: req.body.mail }, per, { new: true, useFindAndModify: false }, (err, doc) => {
    if (err) {
      console.log('Something went wrong when updating data.');
    } else if (doc) {
      res.status(200).send({ auth: true, message: '1 document updated' });
    } else {
      res.status(404).send({ message: 'Resource not found. Please register first.' });
    }
  });
});

// Delete a user
router.delete('/:id', (req, res) => {
  if (!ObjectId.isValid(req.params.id))
    return res.status(400).send(`No record with given id: ${req.params.id}`);

  Person.findByIdAndRemove(req.params.id, { useFindAndModify: false }, (err, docs) => {
    if (!err) { res.send(docs); }
    else { console.log('Error deleting person: ' + JSON.stringify(err, undefined, 2)); }
  });
});

module.exports = router;

You can also clone the finished backend:

git clone https://bitbucket.org/atique12/mongocrud_application_back_end.git

5. Building the Frontend with Angular

The frontend uses Angular with Angular Material for the design. You can clone the finished frontend:

git clone https://bitbucket.org/atique12/mongocrud_application_frnt_end.git

6. Video Walkthrough


About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
Portfolio  |  LinkedIn  |  GitHub

5 comments :

Ishita Jack said...

Excellent data with lots of information. I have bookmarked this page for my future reference. Do share more updates.
Full Stack Developer Course in Chennai
Full Stack Developer Online Course
Full Stack Developer course near me

Cpa Marketing said...

Thanks for the marvelous post! ✅ I really enjoyed reading it, you might be a great author. I will certainly bookmark your blog and definitely will come back sometime soon.
I want to encourage you to continue your great writing.
Apachis online webhosting company Internet Company

Deepa Psikologi said...

MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications. Because all components of the MEAN stack support programs that are written in JavaScript, MEAN applications can be written in one language for both server-side and client-side execution environments. best course to learn MEAN stack

Anil said...

Advanced Topics in Data Analytics at APTRON offer an exciting opportunity for individuals looking to deepen their understanding of this dynamic field. In today's data-driven world, the demand for skilled data analysts is skyrocketing, and APTRON is at the forefront of providing cutting-edge education in this domain.

menka said...

Thanks for the nice post! I really enjoyed reading it, you might be a great author graphice designing training in noida