Angular 5 CRUD Operation Using Node, Express, MongoDB

In this article, we’ll learn to create basic CRUD application using Angular 5, Nodejs, Express and MongoDB NoSQL database.

Introduction

We will create a demo project using Angular CLI for front-end, Node.js and Express for middle-end, and MongoDB for the back-end. In this article, we start from the beginning.

Requirement

  • Visual Studio Code or any IDM for development.
  • Node.js - if you already installed node, then check with node –v command and also check the npm command.
  • MongoDB - In this project, we are using MongoDB database; you can also use SQL or other database.

If you already installed Angular CLI, globally check the version with this command ng -v

Download links

  • Node - https://nodejs.org/en/download/
  • VS code - https://code.visualstudio.com/
  • MongoDB https://www.mongodb.com/download-center

Let’s start and create demo application.

Step 1

Create a new folder with any name, let's say, AngularCRUD. After the folder is created, then press ctrl+shift Right click for opening the command window here.

 
 

Step 2

After the folder opens in the command prompt, run this command for Angular CLI to install in our folder.

npm install -g @angular/cli

Step 3

If installed successfully, then run this command for creating a new application. Let's again set the project name as AngularCRUD.

ng new projectname
 
 

Step 4

When the ng new command is created and installed successfully, change your directory

cd AngularCRUD.

Step 5

Now, we open our project in Visual Studio code with code command like this.

 

Now, we can see VSCode opened automatically.



Step 6

Now run your application by using this command -
 
ng server - o
 
Here, -o stands for opening application in default browser.
 

Step 7

Now, let us install Express and Mongoose body parser using this command.
  • npm install express --save
  • npm install mongoose -- save
  • npm install body-parser --save
 

Step 8

After installing the above three packages, create a new file, server.js.

  1. var express = require('express');  
  2. var path = require("path");   
  3. var bodyParser = require('body-parser');  
  4. var mongo = require("mongoose");  
  5.   
  6. var db = mongo.connect("mongodb://localhost:27017/AngularCRUD", function(err, response){  
  7.    if(err){ console.log( err); }  
  8.    else{ console.log('Connected to ' + db, ' + ', response); }  
  9. });  
  10.   
  11.    
  12. var app = express()  
  13. app.use(bodyParser());  
  14. app.use(bodyParser.json({limit:'5mb'}));   
  15. app.use(bodyParser.urlencoded({extended:true}));  
  16.    
  17.   
  18. app.use(function (req, res, next) {        
  19.      res.setHeader('Access-Control-Allow-Origin''http://localhost:4200');    
  20.      res.setHeader('Access-Control-Allow-Methods''GET, POST, OPTIONS, PUT, PATCH, DELETE');    
  21.      res.setHeader('Access-Control-Allow-Headers''X-Requested-With,content-type');      
  22.      res.setHeader('Access-Control-Allow-Credentials'true);       
  23.      next();  
  24.  });  
  25.   
  26.  var Schema = mongo.Schema;  
  27.   
  28. var UsersSchema = new Schema({      
  29.  name: { type: String   },       
  30.  address: { type: String   },   
  31. },{ versionKey: false });  
  32.    
  33.   
  34. var model = mongo.model('users', UsersSchema, 'users');  
  35.   
  36. app.post("/api/SaveUser",function(req,res){   
  37.  var mod = new model(req.body);  
  38.  if(req.body.mode =="Save")  
  39.  {  
  40.     mod.save(function(err,data){  
  41.       if(err){  
  42.          res.send(err);                
  43.       }  
  44.       else{        
  45.           res.send({data:"Record has been Inserted..!!"});  
  46.       }  
  47.  });  
  48. }  
  49. else   
  50. {  
  51.  model.findByIdAndUpdate(req.body.id, { name: req.body.name, address: req.body.address},  
  52.    function(err,data) {  
  53.    if (err) {  
  54.    res.send(err);         
  55.    }  
  56.    else{        
  57.           res.send({data:"Record has been Updated..!!"});  
  58.      }  
  59.  });  
  60.   
  61.   
  62. }  
  63.  })  
  64.   
  65.  app.post("/api/deleteUser",function(req,res){      
  66.     model.remove({ _id: req.body.id }, function(err) {    
  67.      if(err){    
  68.          res.send(err);    
  69.      }    
  70.      else{      
  71.             res.send({data:"Record has been Deleted..!!"});               
  72.         }    
  73.  });    
  74.    })  
  75.   
  76.   
  77.   
  78.  app.get("/api/getUser",function(req,res){  
  79.     model.find({},function(err,data){  
  80.               if(err){  
  81.                   res.send(err);  
  82.               }  
  83.               else{                
  84.                   res.send(data);  
  85.                   }  
  86.           });  
  87.   })  
  88.   
  89.   
  90. app.listen(8080, function () {  
  91.     
  92.  console.log('Example app listening on port 8080!')  
  93. })  

Step 9

Let us open the project folder in other command prompt and run the node server.js on port 8080.

 

Setp 10

Create a new Angular Service for common AJAX API calling. Use thie commond 

ng g s common –spec=false
 
 

Step 11

Write the following code in common.service.ts for API.
  1. import { Injectable } from '@angular/core';   
  2. import {Http,Response, Headers, RequestOptions } from '@angular/http';   
  3.    
  4. import { Observable } from 'rxjs/Observable';  
  5. import 'rxjs/add/operator/map';  
  6. import 'rxjs/add/operator/do';  
  7.   
  8. @Injectable()  
  9. export class CommonService {  
  10.   
  11.   constructor(private http: Http) { }  
  12.   
  13.   saveUser(user){      
  14.     return this.http.post('http://localhost:8080/api/SaveUser/', user)  
  15.             .map((response: Response) =>response.json())              
  16.   }  
  17.   
  18.   GetUser(){       
  19.     return this.http.get('http://localhost:8080/api/getUser/')  
  20.             .map((response: Response) => response.json())              
  21.   }  
  22.  deleteUser(id){   
  23.     return this.http.post('http://localhost:8080/api/deleteUser/',{'id': id})  
  24.             .map((response: Response) =>response.json())               
  25.   }  
  26.   
  27. }  
Step 12

Now, write the View code in app.module.ts file.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';   
  3.   
  4. import { HttpModule } from '@angular/http';  
  5. import { FormsModule } from '@angular/forms';  
  6.   
  7. import { AppComponent } from './app.component';  
  8.   
  9. import {CommonService} from './common.service';  
  10.   
  11.   
  12. @NgModule({  
  13.   declarations: [  
  14.     AppComponent  
  15.   ],  
  16.   imports: [  
  17.     BrowserModule,HttpModule,FormsModule,  
  18.   ],  
  19.   providers: [CommonService],  
  20.   bootstrap: [AppComponent]  
  21. })  
  22. export class AppModule { }  
Step 13

Code for app.component.html.
  1. <form #userForm="ngForm"   (ngSubmit)="onSave(userForm.value)" novalidate>  
  2.   <p>Is "myForm" valid? {{userForm.valid}}</p>  
  3.  <table border='1'>  
  4. <tr>  
  5. <td>name</td>  
  6. <td>   
  7.     <input name="id" type="hidden"     [(ngModel)]="id" />  
  8.      <input name="name" type="text"  required  [(ngModel)]="name" />  
  9.   
  10.  </td>  
  11. </tr>  
  12.   
  13. <tr>  
  14.     <td>address</td>  
  15.     <td>    <input name="address" required  type="text"   [(ngModel)]="address" /></td>  
  16.     </tr>  
  17.     <tr>  
  18.         <td colspan="2">  
  19.     <input type="submit" value="{{valbutton}}" />  
  20.     </td>  
  21.     </tr>  
  22.  </table>  
  23. </form>   
  24.   
  25. <table border='1'>  
  26.   
  27.   <tr>  
  28.     <td>Id</td>  
  29.     <td>Name</td>  
  30.     <td>Address</td>  
  31.     <td>Edit</td>  
  32.     <td>Delete</td>  
  33.   </tr>  
  34.   <tr *ngFor="let kk of Repdata;let ind = index">  
  35.        
  36.     <td>{{ind + 1}}</td>  
  37.     <td>{{kk.name}}</td>  
  38.     <td>{{kk.address}}</td>  
  39.     <td><a (click)="edit(kk)" style="color:blueviolet">Edit</a></td>  
  40.     <td><a (click)="delete(kk._id)" style="color:blueviolet">Delete</a>  </td>  
  41.   </tr>  
  42. </table>  
  43.   
  44.   
  45.    
Step 14 

Write this code in app.component.ts and remove the existing code from this file.
  1.    
  2. import { Component, OnInit } from '@angular/core';  
  3. import {FormGroup,FormControl,Validators,FormsModule, } from '@angular/forms';  
  4. import {CommonService} from './common.service';  
  5.    
  6. import {Http,Response, Headers, RequestOptions } from '@angular/http';   
  7.   
  8. @Component({  
  9.   selector: 'app-root',  
  10.   templateUrl: './app.component.html',  
  11.   styleUrls: ['./app.component.css']  
  12. })  
  13. export class AppComponent {  
  14.     
  15.      
  16.   constructor(private newService :CommonService,) {   }  
  17.    Repdata;  
  18.    valbutton ="Save";  
  19.    
  20.    
  21. ngOnInit() {    
  22.   this.newService.GetUser().subscribe(data =>  this.Repdata = data)  
  23. }  
  24.   
  25. onSave = function(user,isValid: boolean) {    
  26.  user.mode= this.valbutton;  
  27.   this.newService.saveUser(user)  
  28.   .subscribe(data =>  {  alert(data.data);  
  29.        
  30.     this.ngOnInit();    
  31.   }   
  32.   , error => this.errorMessage = error )  
  33.     
  34. }      
  35. edit = function(kk) {  
  36. this.id = kk._id;  
  37. this.name= kk.name;  
  38. this.address= kk.address;  
  39. this.valbutton ="Update";  
  40. }  
  41.   
  42. delete = function(id) {  
  43. this.newService.deleteUser(id)  
  44. .subscribe(data =>   { alert(data.data) ; this.ngOnInit();}, error => this.errorMessage = error )   
  45. }  
  46.   
  47. }  
We are almost done for performing select, insert, update, delete operation. Now, let us run two servers. The first one is Angular application with command  ng server-o and the second one is to open node.js server.
 
 
We seen the output on borwser port 4200.
 

Summary

In this article, we learned how to create CRUD application with Angular 5 and node. I hope you enjoyed this article. If you have any query related to this code, please comment in the comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all