Crud Using NodeJS / EJS / MongoDB

What is NodeJS ?




Watch the detailed explanation about nodejs , express js and ejs layout & how to use it ?


Complete guide about MongoDb




Watch the detailed explanation about what is database , what is mongodb and how to use mongodb and connecting our project with mongodb


Backend Part




Code for index.js file :

                    
    const express=require("express")

    const app=express()
    app.use(express.json())
    const port=1100
    
    app.listen(port, function () {
        console.log(`server started at port no. ${port}`)
    })
    
    app.get("/",function(req,res){
        res.status(200).json({msg:"Api OK"})
    })
    
    const mongoose=require("mongoose")
    mongoose.connect('mongodb://127.0.0.1:27017/ytcrud').then(()=>{
        console.log("DB Connected");
    }).catch((err)=>{
        console.log(err);
        process.exit(1)
    })
    
    const userSchema = new mongoose.Schema({
        fname: String,
        lname : String    
    });
    
    const Users = mongoose.model("users", userSchema);
    
    app.post("/createUser", async function (req, res) {
        try {
            let { fname,lname } = req.body
            if ( !fname || !lname) {
                res.status(401).json({msg:"Please fill all fields!!!"})
                return
            }
            const user = new Users({
                fname,lname
            });
            await user.save();
            res.status(201).json({msg:'User Saved Successfully'})
        }
        catch (err) {
        console.log(err);
        res.status(500).json({msg:"Server Error"});
        }
    })
    
    app.get("/readUsers", async function (req, res) {
        try {
            const users = await Users.find()      
            res.status(201).json(users);
        }
        catch (err) {
        console.log(err);
        res.status(500).json({msg:"Server Error"});
    }
    })
    
    app.put("/updateUser/:id", async function (req, res) {
        try {
            
            const { fname,lname } = req.body
            const { id } = req.params
    
            if ( !fname || !lname) {
                res.status(401).json("Please fill all fields!!!")
                return
            }
            await Users.findByIdAndUpdate(id,{fname,lname})
            res.status(201).json({msg:'User Successfully Updated'})    
        }
        catch (err) {
            console.log(err);
            res.status(500).json({msg:"Server Error"});
        }
    })
    
    app.delete("/deleteUser/:id", async function (req, res) {
        try {
            const { id } = req.params
    
            await Users.findByIdAndDelete(id)
            res.status(201).json({msg:'User Successfully Deleted'})    
        }
        catch (err) {
            console.log(err);
            res.status(500).json({msg:"Server Error"});
        }
    })
  
                


Frontend Part




Html Code for dashboard.ejs file :

                    
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://kit.fontawesome.com/c123228cd1.js" crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <title>Person's Details</title>
    <style>
    @import url("https://fonts.googleapis.com/css2?family=Nunito&display=swap");



    body {
        font-family: "Nunito", sans-serif;
    }
    
    </style>
</head>
<body>

    
    
    <div class="container">
    <h3 class="alert alert-info mt-5 text-center fw-bold w-50 mx-auto">CRUD USING NODE</h3>
    <div class="row p-3 rounded-3 border border-3">
    
    <div class="col-lg-5 py-3 " >
        <h2 class="text-center alert alert-warning">Add Person</h2>
        <input class="d-none" type="text" id="id" placeholder="Enter Id" />

        <div class="mb-3 mt-5 ">
        <label for="exampleInputEmail1" class="form-label">First Name</label>
        <input type="text" class="form-control" id="fname" aria-describedby="emailHelp">
        </div>
        <div class="mb-5 ">
        <label for="exampleInputEmail1" class="form-label">Last Name</label>
        <input type="text" class="form-control" id="lname" aria-describedby="emailHelp">
        </div>
        

    
        <div style="text-align: center">
        <button
            class="btn btn-danger submit"
            value="Submit"
            id="submit"
            onclick="storedata()"
        >
            Submit
        </button>
        <button class="btn  btn-success reset" value="Reset" onclick="reset()">Reset</button>
        </div>
    </div>

    <div class="col-lg-7 py-3 text-center">
        <h2 class="text-center alert alert-warning">Person Details</h2>

        <table class="table table-stripped rounded-3">
        <tr style="background-color: aliceblue !important;">
            <th class="d-none">Id</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Actions</th>
        </tr>
        <tbody id="screen"></tbody>
        </table>
    </div>
    </div>
    </div>
</body>

</html>
  
                


Javascript Code : Paste this code at the end of html before closing of body tag enclosed within script tag.
                                   

    async function read(){      
        const response = await fetch("/readUsers");  
        if (!response.ok) {        
            const data=await response.json()       
            alert(data.msg);
            return
        }
        const data= await response.json()
        let screen = document.getElementById("screen")
        screen.innerHTML = "";
        for (let i = 0; i < data.length; i++) {
            screen.innerHTML += `
            <tr>
                <td class="d-none">${data[i]._id}</td>
                <td>${data[i].fname}</td>
                <td>${data[i].lname}</td>
                <td>
                <button class="btn btn-danger" onclick="editdata(this)"> Edit</button>
                <button class="btn btn-warning" onclick="deletedata(this)">Delete</button>
                </td>
            </tr>
            `;
        }  
        }
        read()
    
        async function storedata(){
    let submit = document.getElementById("submit").innerText;
    if (submit == "Submit") 
    {
        const fname = document.getElementById("fname").value;
        const lname = document.getElementById("lname").value;
        if (fname == "" || lname=="") 
        {
        alert("Please fill all fields");
        return
        } 
        const response = await fetch("/createUser",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body:JSON.stringify({
                fname,lname
            })
            }
            );
        const data=await response.json()       
        alert(data.msg);    
        await read();    
    } 
    else
    {
        update();
    }
    reset();
    }
    
    async function editdata(e) 
    {
    let ele = e.parentNode.parentNode;
    document.getElementById("id").value = ele.children[0].innerText;
    document.getElementById("fname").value = ele.children[1].innerText;
    document.getElementById("lname").value = ele.children[2].innerText;
    document.getElementById("submit").innerText = "Update";
    }
    
    function reset() {
    document.getElementById("id").value='';
    document.getElementById("fname").value = '';
    document.getElementById("lname").value = '';  
    document.getElementById("submit").innerText = 'Submit';
    }
    
    async function update(){
    const id = document.getElementById("id").value;
    const fname = document.getElementById("fname").value;
    const lname = document.getElementById("lname").value;
    if (fname == "" || lname == "")
    {
        alert("Please fill all fields");
        return
    } 
    const response = await fetch(`/updateUser/${id}`,{
            method: "PUT",
            headers:{
                "Content-Type": "application/json",
            },
            body:JSON.stringify({
                fname,lname
            })
            });  
    const data=await response.json()       
    alert(data.msg); 
    await read();
    reset();
    }
    
    async function deletedata(e) {
    if (confirm('Are you sure ?')) {    
        const id = e.parentNode.parentNode.children[0].innerText;
        const response = await fetch(`/deleteUser/${id}`,{
            method: "DELETE"
            });  
        const data=await response.json()       
        alert(data.msg); 
        await read();
        reset();
        }
    }
 
                            
      
                    





Contact Us

REACH US

SERVICES

  • CODING
  • ON-LINE PREPARATION
  • JAVA & PYTHON

ADDRESS

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+ 919839520987
Email:info@alexsir.com