Home Node JS Build a Full-Stack Node.js MongoDB CRUD App with JWT Authentication

Build a Full-Stack Node.js MongoDB CRUD App with JWT Authentication

8 min read
0
0
423

In this tutorial, we will teach the process of building a full-stack application using Node.js, MongoDB, and JWT authentication. This Application will allow users to perform CRUD operations (Create, Read, Update, Delete) on a MongoDB database, while also implementing user authentication using JSON Web Tokens (JWT) Step by Step.I have attached the complete Video Below. Follow the Instruction and do the project.

Nodejs express

Install Node JS

npm init

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

Install the bcrypt

npm i bcrypt

Install the jsonwebtoken

npm i jsonwebtoken

Create Server and Establish the Database Connection

First Create the Application index.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 dbsmss.attached the db connection below.

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://127.0.0.1:27017/dbsmss";

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.using following command

node index.js

After that Create the Folder Routes inside the Route folder create Route file

router.js

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

router.post("/students/login", async (req,res)=>{
    try{
        const student = await Student.findByCredentials(req.body.name,req.body.password)

        const token = await student.generateAuthToken()

        res.send({student,token})

      
    }
    catch(error)
    {
        res.status(401).send()
    }
})


//Add Rrcords
router.post('/student/create', 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',auth, async(req,res)=>{
   
   try{

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

});


//find records

router.get('/students/me',auth, 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',auth, 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
        },
        password:{
            type: String,
            trim: true,
            required : true
        },
        tokens:[
            {
                token:{
                    type:String,
                }
            }
        ]
    }
)


studentSchema.pre("save", async function (next) {
    const student = this;
    if (student.isModified("password")) {
      student.password = await bcrypt.hash(student.password, 8);
    }
    next();
  });

  studentSchema.statics.findByCredentials = async (name,password)=>{
    const student = await Student.findOne({name})
   
           
        const isMatch = await bcrypt.compare(password,student.password)
            if(!isMatch)
            {
                throw new Error()
            }
            return student
  }

  studentSchema.methods.generateAuthToken = async function(){
    const student = this;
    const token = jwt.sign({_id: student._id.toString()},"mysecret")
    student.tokens = student.tokens.concat({token})
    await student.save()
    return token;
}


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


Auth

create the folder middleware inside the folder implement the auth

const jwt = require("jsonwebtoken")
const Student = require("../src/student/studentModel")
const auth = async(req,res,next)=>{
    try
    {
      const token =   req.header("Authorization").replace("Bearer ","")
      const decoded =  jwt.verify(token,"john2")
      const student = await Student.findOne(
      {
        _id:decoded._id,
        "tokens.token":token
      })
      if(!student){
        throw new Error()
      }
      req.student = student;
      next()
    }
    catch(error)
    {
        res.status(401).send({error: "Please Auth"})
    }
}

module.exports = auth

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

 

Load More Related Articles
Load More By admin
Load More In Node JS

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Employee Working Hours Calculation System using C#.net

Initialize the employee number, Hourswork,and Hoursrate to calculate a grosswage use the f…