DEV Community

Sachin kumar singh
Sachin kumar singh

Posted on

How to create a mern stack Crud application ?

Introduction
In this tutorial we are going to learn that how we can create a beginners friendly crud application with the help of mern-stack.
Prior knowledge
To follow this tutorial you should have minimum knowledge of react,node and mongodb. This are the technologies that together combine to form a mern stack.
To get the complete source code visit my github account

GitHub logo Sachinsingh101 / Mern-Crud-App

This is an Advance Crud-app made with mern-stack, You can perform any of crud operations in this app.You can colaborate with me for future projects coming soon....


THE FRONTEND
step-1
First of open your vs code editor or any other editor you like
then create a folder named it as mern stack crud.
Inside this folder create two folders named it as client or server.

Mern stack crud app
step-2
Inside client folder we will create our react application.
open command line and Type ""npx create-react-app app" then hit enter to create a basic react application inside client folder.
after this you folder structure should look like this.

React node.js and mongodb
step-3
After the step mention above navigate to src folder and create a folder named it as component folder.
In this folder we will keep our all the components like 'Add user componet','edit user','all user' or the navbar component

Mern stack
step-4
Navigate to src folder then component folder and create a file or component named it as 'add user' component
then write you code or copy the code mention below to create a basic 'add user' interface

import {useState} from 'react'
import axios from 'axios'
function Adduser(){
    const [user,setuser]=useState({
        Name:"",
        email:"",
        number:""
    });
    function changeHandler1(e){
        setuser({
            ...user,Name:e.target.value
        })

    }
    function changeHandler2(e){
        setuser({
            ...user,email:e.target.value
        })
    }
    function changeHandler3(e){
        setuser({
            ...user,number:e.target.value
        })
    }
    function submitHandler(e){
        e.preventDefault()
        const userdata={
            name:user.Name,
            email:user.email,
            number:user.number

        }
        try{
            axios.post('http://localhost:4000/add',userdata);
            setuser({
                Name:"",
                Email:"",
                number:""
            });
            alert("user added successfully !!!");
        }catch (err){
            console.log("react aios post error",err);
        }


        console.log(userdata);

    }


    return(
        <>
          <div className="container m-5">
            <h1 className="text-center text-dark">Add User</h1>
            <form onSubmit={submitHandler}>
             <input type="text" placeholder="Enter your Name" name="name" className="form-control m-3" onChange={changeHandler1} value={user.Name} required></input>
             <input type="email" placeholder="Enter your Email" name="email" className="form-control m-3" onChange={changeHandler2} value={user.Email} required></input>
             <input type="number" placeholder="Enter your Phone number" name="number" className="form-control m-3" onChange={changeHandler3} value={user.number} required></input>
             <input  type="submit"  className="btn btn-primary form-control m-3" ></input>
             <input type="reset" className="btn btn-danger form-control m-3"></input>
            </form>
          </div>
        </>
    )
}
export default Adduser;

Enter fullscreen mode Exit fullscreen mode

Eplained:- In above code we are first creating a form after we are creating state to hold the input of the forms field then post these data to backend with the help of aios.
step-5
similarly create a file named as 'alluser.js' inside component folder and copy the code below or write you own code to get a basic all user interface

import {useState,useEffect} from 'react'
import {Link} from 'react-router-dom'
import axios from 'axios'
function Getallusers(props){

    const [Alluser,setuser]=useState({
        students:[]
    })
    useEffect(()=>{
        try{
            axios.get('http://localhost:4000/getallusers').then(res=>{
                setuser({
                    students:res.data
                });

            })
        }catch(err){
            console.log("error while getting users",err);
       }
    }) 


    return(
        <> 
          <table className='container-fluid text-center bg-light p-3'>
            <thead >
                <tr className='row p-3'>
                    <th className='col'>Name</th>
                    <th className='col'>Email</th>
                    <th className='col'>Phone number</th>
                </tr>
            </thead>
          </table>
          <table className='container-fluid'>
            <thead >

                {
                        Alluser.students.reverse().map(function(value,i){
                            return <tr className='bg-danger text-white text-center border border-dark'>
                                      <td className='border-end border-dark'>{value.name}</td>
                                      <td className='border-end border-dark'>{value.email}</td>
                                      <td className='border-end border-dark'>{value.number}</td>
                                      <Link to={`/Edit/${value._id}`} className='btn btn-danger text-dark' onClick={props.name} id="edit">Action</Link>
                                    </tr>

                        })
                    }
            </thead>
          </table>
        </>
    )
}
export default Getallusers;

Enter fullscreen mode Exit fullscreen mode

Eplained:- In the above code first we create a table then make a get request with aios then save the response to the state and use it in the table to show the alluser in our app.
step-6
similarly create a file named it as 'edituser.js' inside component folder and write your own code or paste it from here to create a edit user interface

import axios from "axios";
import {  useParams } from "react-router-dom";
import {useState,useEffect} from 'react';


function Edituser(){
    const [newdata,setnewdata]=useState({
        Name:"",
        Email:"",
        number:""
    });
    function changeHandler1(e){
        setnewdata({
           ...newdata, Name:e.target.value
        });
    }
    function changeHandler2(e){
        setnewdata({
           ...newdata, Email:e.target.value
        });
    }
    function changeHandler3(e){
        setnewdata({
           ...newdata, number:e.target.value
        });
    }
    const routeParams=useParams();
    const id=routeParams.id;
    function getsingledata(){
        axios.get(`http://localhost:4000/getsingleuser/${id}`).then(res=>{
            setnewdata({
                Name:res.data.name,
                Email:res.data.email,
                number:res.data.number
            });
            console.log(newdata);
        })
        console.log(id);
    }
    useEffect(()=>{
        getsingledata();
    },[]);
    function submitHandler(e){
        e.preventDefault()
        const updatedData={
            name:newdata.Name,
            email:newdata.Email,
            number:newdata.number
        }
        try{
            axios.put(`http://localhost:4000/Edit/${id}`,updatedData);
            setnewdata({
                Name:"",
                Email:"",
                number:""
            });
            alert("data updated successfully !!!");
        }catch(err){
            console.log("error while updating",err);
        }    
    }
    function deleteuser(){
        try {
            axios.delete(`http://localhost:4000/deleteuser/${id}`);
            alert("user deleted successfully !!!!");
            setnewdata({
                Name:"",
                Email:"",
                number:""
            });
            alert("user updated successfully !!!!1");
        }catch(err){
            console.log("error while making delete request",err);
        }

    }


    return(
        <>
          <div className="container mt-5">
          <form onSubmit={submitHandler}>
             <h1 className="text-center">Edit User</h1>
             <input type="text" placeholder="Enter your Name" name="name" className="form-control m-3" value={newdata.Name} required onChange={changeHandler1}></input>
             <input type="email" placeholder="Enter your Email" name="email" className="form-control m-3" value={newdata.Email}required onChange={changeHandler2}></input>
             <input type="number" placeholder="Enter your Phone number" name="number" className="form-control m-3" value={newdata.number} required onChange={changeHandler3}></input>
             <input  type="submit" className="btn btn-primary form-control m-3"></input>
         </form>
         <h5 className="text-center text-muted">OR</h5>
         <div className="btn btn-outline-danger form-control m-3 " onClick={deleteuser}>Delete</div>
          </div>

        </>
    );

}
export default Edituser;
Enter fullscreen mode Exit fullscreen mode

eplained:- In the above code first we make a form then make a get request to fill up the form with the user details then maka a put request after user make some changes to his data to save it again to the database.

step-7
Import these componets to app.js file.
after that your app.js file should look like this.

// import logo from './logo.svg';
import {Routes,Route, redirect} from 'react-router-dom'
import './App.css';
import Navbar from './components/navbar.js';
import Adduser from './components/adduser';
import Getallusers from './components/alluser';
import Edituser from './components/edituser.js'

function App() {

  return (
    <>
      <Navbar/>
      <Routes>
        <Route path="/" element={<Adduser/>}/>
        <Route path="/get" element={<Getallusers/>}></Route>
        <Route path={`/Edit/:id`} element={<Edituser/>}></Route>
        {/* <Route path="/redirect"></Route> */}
      </Routes>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now our frontend part completed and this is first part of our tutorial.

THE BACKEND
step-1
Open the command line and navigate to server folder then install the dependencies mention below to start working with the backend.
first step:- npm init then
1.Express(npm i epress)
2.mongoose(npm i mongoose)
3.nodemon(npm i nodemon)
4.cors(npm i cors)
5.body-parser(npm i body-parser)
6.dotend(npm i dotend)
Note:- you can also install these dependencies in one go just type
'npm i epress mongoose nodemon cors body-parser dotenv '
and thats all we are ready to work with backend.

step-2
Inside server folder create the following folder or file mention below
1.routes
2.database
3.controllers
4.'.env'
5.app.js

setp-3
Navigate to app.js file and paste the code given below

import cors from 'cors'
import express from "express";
import bodyParser  from 'body-parser';
import dotenv from 'dotenv'
dotenv.config();
import router from './routes/userroute.js'
import connection from './database/connectDB.js';
import './database/model.js';
const app=express();
app.use(cors());
app.use(bodyParser.json({extended:true}));
app.use(bodyParser.urlencoded({extended:true}));
const port=process.env.PORT || '4000'
const DATABASE_URL=process.env.DATABASE_URL


app.get('/',(req,res)=>{
    res.send("Hello world from express");
})

app.use('/',router);
connection(DATABASE_URL)
app.listen(port,()=>{
    console.log("listening to 3000 port");
})
Enter fullscreen mode Exit fullscreen mode

step-4
Navigate to route folder and create userroute.js file and paste the following code

import express from "express";
import {postfunction , getfunction , Editfunction ,Getsingleuser, Deleteuser} from "../controllers/usercontroller.js";
const router=express.Router();

router.all('/add',postfunction);
router.get('/getallusers',getfunction);
router.put('/Edit/:id',Editfunction);
router.get('/getsingleuser/:id',Getsingleuser);
router.delete('/deleteuser/:id',Deleteuser);

export default router;


Enter fullscreen mode Exit fullscreen mode

step-5
Navigate to controllers folder and create controller.js file and paste the following code inside it

import userModel from "../database/model.js";


const postfunction =  (request,response)=>{
   const data=request.body;
   const userdata=new userModel(data);
   userdata.save()
   response.send(data);
   console.log(data);

}
const getfunction=(req,res)=>{
   // res.send("hello world");
   const allusers=userModel.find((error,data)=>{
      if(error){
         return next(error)
      }else{
         res.json(data);
      }
   });

}

const Editfunction=async (req,res)=>{
   try{
      const newdata=req.body;
      const param=req.params;
      const update= await userModel.findByIdAndUpdate(param.id,newdata);
      console.log(newdata,update)
   }catch(err){
      console.log("error while updating data",err);
   }

}
const Getsingleuser=async(req,res)=>{
   try{
      const Data= await userModel.findById(req.params.id,'name email number');
      res.json(Data);
      console.log(Data);
      // console.log(Data);
   }catch(err){
      console.log("error while getting each  user",err);
   }
}
const Deleteuser= async (req,res)=>{
   try{
      const id=req.params.id;
      await userModel.findByIdAndDelete(id);
      console.log(req.params.id);
   }catch(err){
      console.log("error while deleting user",err);
   }
}

export {getfunction,postfunction,Editfunction,Getsingleuser,Deleteuser}

Enter fullscreen mode Exit fullscreen mode

step-6
Navigate to database folder and create connectDb.js file and paste the following code inside it to connect with database

import mongoose from 'mongoose'

const connection = async(DATABASE_URL)=>{
    try{
        const Db_optiion={
            Dbname:"Sachimaa"
        }
        await mongoose.connect(DATABASE_URL,Db_optiion);
        console.log("Database connected successfully");
    } catch(err){
        console.log("error while connecting to Database ",err);
    }
}

export default connection;
Enter fullscreen mode Exit fullscreen mode

stpe-7
Inside databse folder create another file named it as module.js and paste the following code given below

import mongoose from "mongoose";

const userSchema=new mongoose.Schema({
    name:{type:String,required:true},
    email:{type:String,required:true},
    number:{type:Number,required:true}
})

const userModel= mongoose.model('user',userSchema);

export default userModel;
Enter fullscreen mode Exit fullscreen mode

step-8
Now our backend is completed and our Crud app is ready
You can host it to github or any other platform.

Top comments (1)

Collapse
 
sachinsingh101 profile image
Sachin kumar singh • Edited

Hope that this tutorial will help you to get started with the mern stack.