Angular CRUD APP MEAN Stack Part – I

In this tutorial, we discuss how to create MEAN stack CRUD (create, read, update, delete) operations in angular application. For the server-side, we use Mongo DB, Express JS & Node in frontend we use angular.
Let’s First we discuss on what is “MEAN stack”

  • Mongo DB: It’s an open-source NoSQL cross-platform document-oriented database. Which store data in Json Format. In these application we connect our database to “cloud.mongodb.com”
  • Express JS: Using these we create web-based application framework work with Node JS. It helps to create REST API
  • Angular: It’s front-end framework using typescript. We use for display data.
  • Node JS: It’s an open source development platform for executing JavaScript code outside of a browser.



In this article, we discuss on add, update delete, and listing of employees detail. For that first, we need to set up the server-side code. First, we create a folder called server


mkdir server

After creating a folder we need to go inside that folder then we need to create a package.json file for that we need to run the below command.


npm init -y

It will generate a package.json file with the required configuration. We need to install some npm modules

  1. body-parser: These module is a used for JSON parsing middleware. It helps to parse the JSON data, plain text or a whole object.
  2. Express.js: Its helps in creating web applications and RESTful APIs.
  3. CORS: Its known as the express js middleware. It allows enabling CROS origion communication with multiple optios.
  4. Mongoose: It help to communicate with MongoDB database.

To install above module run below command in the server folder.


npm install --save body-parser cors express mongoose

After installing above module we need one more module called “nodemon”. these package helps restarts the server automatically every time we make a change in server side we donot need to restsrt every time when we change anything on server side code.


npm install nodemon --save-dev

After installing the module let’s start create server side code. For that first we need to create server.js file. In that file we add database connection , Api calling code. Below code need to add in the server.js file.


let express = require('express'),
   path = require('path'),
   mongoose = require('mongoose'),
   cors = require('cors'),
   bodyParser = require('body-parser'),
   dbConfig = require('./database/db');

// Connecting with mongo db
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
   useNewUrlParser: true
}).then(() => {
      console.log('Database sucessfully connected')
   },
   error => {
      console.log('Database could not connected: ' + error)
   }
)

// Setting up port with express js
const employeeRoute = require('../server/routes/employee.route')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: false
}));
app.use(cors()); 
app.use(express.static(path.join(__dirname, 'dist/crud-mean')));
app.use('/', express.static(path.join(__dirname, 'dist/crud-mean')));
app.use('/api', employeeRoute)

// Create port
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
   next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message); // Log error message in our server's console
  if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
  res.status(err.statusCode).send(err.message); // All HTTP requests must have a response, so let's send back an error with its status code and message
});

In above file we have added database config file path dbConfig = require('./database/db') We need to create database folder in that folder create db.js file. In that file we need to add the datbase connection for mongodb.


//replace  when you create
//replace   Database name 
module.exports = {
  db: 'mongodb+srv://curd_db_1:@cluster0.nxvfq.mongodb.net/?retryWrites=true&w=majority'
};

Here I have used cloud MongoDB connection. How to create an account and configure a database and how to get a connection string to connect that database you need to watch below video. step by step process display in the video.

Now we need to create Model with Mongoose JS
For that we need to create folder model inserver folder. thane we need to create Employee.js for connect colloection. Define their Schema for that collection.


const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema
let Employee = new Schema({
   name: {
      type: String
   },
   email: {
      type: String
   },
   designation: {
      type: String
   },
   phoneNumber: {
      type: Number
   }
}, {
   collection: 'employees'
})
module.exports = mongoose.model('Employee', Employee)

Now we need to create API to communicate RESTful APIs using Express JS Routes
For that we create”employee.route.js” file in Routers folder in that we have add main logic for add, update, delete and list api which we call from our angular application.
Add below code in that file employee.route.js


const express = require('express');
const app = express();
const employeeRoute = express.Router();

// Employee model
let Employee = require('../models/Employee');

// Add Employee
employeeRoute.route('/create').post((req, res, next) => {
  Employee.create(req.body, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
});

// Get All Employees
employeeRoute.route('/').get((req, res,next) => {
  Employee.find((error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})

// Get single employee
employeeRoute.route('/read/:id').get((req, res,next) => {
  Employee.findById(req.params.id, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})


// Update employee
employeeRoute.route('/update/:id').put((req, res, next) => {
  Employee.findByIdAndUpdate(req.params.id, {
    $set: req.body
  }, (error, data) => {
    if (error) {
      return next(error);
      console.log(error)
    } else {
      res.json(data)
      console.log('Data updated successfully')
    }
  })
})

// Delete employee
employeeRoute.route('/delete/:id').delete((req, res, next) => {
  Employee.findOneAndRemove(req.params.id, (error, data) => {
    if (error) {
      return next(error);
    } else {
      res.status(200).json({
        msg: data
      })
    }
  })
})

module.exports = employeeRoute;



Now server-side code is done. Need to check server-side API working or not for that we need to start nodemon server.
To start nodemonserver go to the server folder then run below command


npx nodemon server.js

You can dsiplay the below screen. If datbase configration added propertly then it display datbase connection successfully or it throws error if not properly configured.

In the next part, we discuss how to see the APT it’s working or not. and display the data of employees in our angular application.

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 2
  •  
  •