Node JS

Angular 16 Node js MongoDB Crud App

This tutorial will teach you crud application using angularjs node js mongodb.node js mongodb crud along with angular is famous full stack development in the future because very easy step make restful api we will start from the node js angular install process to make the restfulapi project along with video tutorial so you easy to learn it i attached the video below of articles.

nodejs express angular Learn Learn

First Step What you have to do is you to divide the Front-End and Back-End.

Front-End – Angular JS

BackEnd – Node JS

Create the folder myprojects. inside the folder Frond end project  you maintaining with the separate folder.
Backend project you maintaining with the separate folder.

Install Node JS

Create  a new Project type  the command on the command prompt.

Type the Command on Console.

npm init

and create your project. After project has been created you see the package.json file.

Then open the project in to the VS Code Editor by typing the following command

code .

after open up the project in to the vscode editor

Install the Express Server as back end server

npm i express

Install the bodyParser

npm i body-parser

Install the mongoDB as database

npm i mongoose

Create Server and Establish the Database Connection

First Create the Application server.js which manage the ports and libraries and database connection of the project. We have created the database on mongodb atlas Cloud database service which name test.attached the db connection below.

index.js

const express = require("express")
const mongoose = require("mongoose")
var routers = require('./routes/routes');
const bodyParser = require("body-parser")

const app = express()
const cors = require('cors');
const port = 5000;

const mongodatabaseURL ="mongodb+srv://kobiram:mongoabc@cluster0.cqfkrbj.mongodb.net/?retryWrites=true&w=majority";

mongoose.connect(mongodatabaseURL,{
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const connection = mongoose.connection


app.listen(port,()=>{
    console.log("Server is running port" +port);
})


connection.once("open",()=>{
    console.log("MongoDb Connected!!!......")
});

app.use(cors());
app.use(bodyParser.json());
app.use(routers);


After that you can run the server type by the following command.

node index.js

You can get the result as

MongoDb Connected

after that make the new folder route and inside the folder create the page route.js. route.js page which use to manage the all the restapis related to crud operations.

Create Routes

const express = require("express")
const router = express.Router();
var studentModel = require('../src/student/studentModel');


//Add Records
router.post('/student/create',auth, async (req, res) => {
    try {
      const student = new studentModel(req.body);
      await student.validate(); // Validate the input data
  
      await student.save();
      res.status(201).send({
        status: true,
        message: "Student Created!!!!!!!!!!!!!!!!"
      });
    } catch (error) {
      res.status(400).send(error);
    }
  });


//View Records
router.get('/students', async(req,res)=>{
   
   try{

        const students = await studentModel.find({});
        res.send(students);
   }
   catch(error)
   {
        res.status(400).send(error);
   }

});


//find records

router.get('/students/:id', async(req,res)=>{
   
    try{
         const _id = req.student._id;
         const students = await studentModel.findById({_id});

        if(!students)
        {
            return res.status(404).send();
        }  
        return res.status(200).send(students); 
    }
    catch(error)
    {
         res.status(400).send(error);
 
    }

 });


//update records
 router.patch('/students/:id', async(req,res)=>{
   
    try{
        const _id = req.params.id;
        const body = req.body;
        const updatestudents = await studentModel.findByIdAndUpdate(_id,body,{new:true});

        if(!updatestudents)
        {
            return res.status(404).send();
        }  
     
        res.status(201).send(
            {
                "status" : true,
                "message" : "Student updateddd!!!!!!!!!!!!!!!!"
            });
 
    }
    catch(error)
    {
         res.status(400).send(error);
 
    }

 
 });


//delete records
 router.delete('/students/:id', async(req,res)=>{
   
    try{
            const _id = req.params.id;
        
         const deletestudents = await studentModel.findByIdAndDelete(_id);

        if(!deletestudents)
        {
            return res.status(404).send();
        }  
       
        res.status(201).send(
            {
                "status" : true,
                "message" : "Student Deletedd!!!!!!!!!!!!!!!!"
            });
    }
    catch(error)
    {
         res.status(400).send(error);
 
    }
 });


 router.post('/students/logout',auth, async(req,res)=>{
   
    try{
            req.student.tokens = req.student.tokens.filter((token)=>{
                return token.token !== req.token;
            })

            await req.student.save()
            res.send()
    }
    catch(error)
    {
         res.status(400).send(error);
 
    }
 });

module.exports = router;

Create Model

StudentModel.js

const mongoose = require("mongoose")
const bcrypt = require( 'bcrypt' );

const jwt = require("jsonwebtoken")


var Schema  = mongoose.Schema;


var studentSchema = new Schema(
    {
        name: {
                type:String,
                required: true
        },
        address: {
            type:String,
            required: true
        },
        phone: {
            type:Number,
            required: true
        }
   
    }
)

module.exports = mongoose.model('student',studentSchema);

Angular

Angular is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.

Installing Angular CLI

npm install -g @angular/cli

After that create the new Project of Angular running by the following command

ng new frond-end

Select the SCSS Style for the Advanced CSS and Press Enter Key.

After complete the installation then run the project using following command.

ng serve

Now you see the Angular Welcome Page.

After that open the Angular project into VS code editor.

now you can see the following file structure

Creating a new Component student type by following command

ng g c student

After that Add the  Bootstrap Styles.go to the bootstrap official website and copy the CSS style then paste the style in to index.html file inside the <head> 

<head>
  <meta charset="utf-8">
  <title>FrontendProject</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">

</head>

app.module.ts

FormModule
HttpClientModule

add these module into the app.module.ts file  then only we will manage the forms and Http requests.

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StudentcrudComponent } from './studentcrud/studentcrud.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent,
    StudentcrudComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

After that open up the student.component.html

student.component.html

<div class="container mt-4" >
  <div class="card">
          <h1>Student Registation</h1>
<form>
  <div class="form-group">
    <label>Name</label>
    <input type="text" [(ngModel)]="name" [ngModelOptions]="{standalone: true}"  class="form-control" id="name" placeholder="Enter Name"> 
  </div>
  <div class="form-group">
      <label>Address</label>
      <input type="text" class="form-control"  [(ngModel)]="address" [ngModelOptions]="{standalone: true}" id="address" placeholder="Enter Address"> 
    </div>
    <div class="form-group">
      <label>Phone</label>
      <input type="text" class="form-control" [(ngModel)]="phone" [ngModelOptions]="{standalone: true}" id="phone" placeholder="Enter Phone"> 
    </div>
  <button type="submit" (click)="save()" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="container mt-4" >
<h1>Student Table</h1>
<table class="table">
<thead>    
<tr>
    <th scope="col">Name</th>
    <th scope="col">Address</th>
    <th scope="col">Phone</th>  
    <th scope="col">Option</th>
  </tr>
</thead>
<tbody>
    <tr *ngFor="let StudentItem of StudentArray">
    <td>{{StudentItem.name  | uppercase}}</td>
    <td>{{StudentItem.address }}</td>
    <td>{{StudentItem.phone }}</td>
    <td>
      <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button>
      <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button>            
    </td>
  </tr>          
</tbody>
</table>
</div>

studentcrud.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.scss']
})
export class StudentComponent {


StudentArray : any[] = [];
  currentStudentID = "";
  name: string ="";
  address: string ="";
  phone: string ="";
  
  constructor(private http: HttpClient ) 
  {
    this.getAllStudent();
  }
  getAllStudent() {
    this.http.get("http://localhost:5000/students")
    .subscribe((resultData: any)=>
    {
       
        console.log(resultData);
        this.StudentArray = resultData;
    });
  }
  setUpdate(data: any) 
  {
   this.name = data.name;
   this.address = data.address;
   this.phone = data.phone;
   this.currentStudentID = data._id;
  
  }
  UpdateRecords()
  {
    let bodyData = {
      "name" : this.name,
      "address" : this.address,
      "phone" : this.phone,
    };
    
    this.http.patch("http://localhost:5000/students"+ "/"+this.currentStudentID,bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Updateddd")
        this.getAllStudent();
      
    });
  }
  
  setDelete(data: any) {
    this.http.delete("http://localhost:5000/students"+ "/"+ data._id).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Deletedddd")
        this.getAllStudent();
   
    });
    }
    
  save()
  {
    if(this.currentStudentID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }       
  }
register()
  {
    let bodyData = {
      "name" : this.name,
      "address" : this.address,
      "phone" : this.phone, 
  };
    this.http.post("http://localhost:5000/student/create",bodyData).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Successfully")
         //this.getAllEmployee();
        this.name = '';
        this.address = '';
        this.phone  = '';
        this.getAllStudent();
    });
  }
}

Related Tutorials
Nodejs React with MongoDb Crud App
https://www.tutussfunny.com/mern-full-stack-complete-application-mongodb-express-react-node-js/

Nodejs Vuejs with MongoDb Crud App
https://www.tutussfunny.com/mevn-full-stack-complete-application-mongodb-express-vue-js-node-js/

Nodejs Angular with Mysql Crud Application
https://www.tutussfunny.com/nodejs-angular-with-mysql-crud-application/

Nodejs React with Mysql Crud Application
https://www.tutussfunny.com/nodejs-react-with-mysql-crud-application/

i have attached the video link below. which will do this tutorials step by step.

 

admin

Recent Posts

Employee Working Hours Calculation System using C#.net

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the following condition. if…

13 hours ago

Java Payroll System Calculate Employee Overtime

Act as a Java developer to create a program that calculates the gross wage for…

3 days ago

Employee Working Hours Calculation System using Java

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the following condition. if…

3 days ago

Laravel 11 School Management System

In this tutorial, we will teach you how to create a simple school management system…

1 week ago

How to Make Admin Panel Using React MUI

I have design the Admin Basic templete using React MUI Design Admin Dashboard and Login.Here…

3 weeks ago

Install Laravel Breeze for Authentication Using Laravel 11

In this tutorial ,i am to going teach the Laravel Breeze.Laravel Breeze provides a simple…

3 weeks ago