From Zero to Hero: Creating a MERN CRUD Application

Find the best article for the RESTapi CRUD
npm init -y

npm i express

npm i esm

npm i nodemon -D

npm i dotenv

create server.js make script -> "dev":"nodemon -r esm <file name>" ->

for production script: "start": "node -r esm server.js"

follow the model view controller structure to maintain good-looking readable code

next, connect to the MongoDB with the inside the server js

create a folder name config, create a file name index.js

#config, index.js
import dotenv from 'dotenv';
dotenv.config();

export const {
    APP_KEY,
    MONGODB
} = process.env

now take care of the server.js in the root file

connect with MongoDB

app.listen(port, () => console.log(`listening on port ${port}`));

mongoose .connect(ECOMDB) .then(() => console.log("DB Connected! now get lost")) .catch((err) => { CustomeErrorHandler.DbError( "you can not connect database with backend, please die in peace!" ); });

create router here

app.use("/ecom", router);

to take JSON body

app.use(express.json());

mongoose 6.9+ connection string using async and await

import express from 'express';
import { APP_KEY, MONGODB } from './config';
import mongoose from 'mongoose';
import router from './router';
const app = express();
app.use(express.json());
app.use("/api", router);
app.listen(APP_KEY, async()=>{
    console.log("Connection to the DB");
    try{
        await mongoose.connect(MONGODB);
        console.log("Connection Successful")
    }catch(err){
        console.log("Error in DB connection")
    }
});

The best practice is to import all dotenv through the config folder this way,

import dotenv from 'dotenv';
dotenv.config();
export const {
    APP_KEY,
    MONGODB
} = process.env

now the task is to create all the routers inside the router folder. the file name will be index.js

Always remember that we only need to write functions inside the controller. means what is the purpose of the target route. This function will be called inside the routes.

before creating the function finish the model.

Here I am giving an example, of how a model can be created.

#user model
import mongoose from "mongoose";
const MySchema = mongoose.Schema;
const userSchema = new MySchema({
    name: { type: String, required: true },
    email: { type: String, required: true },
    phone: { type: Number, required: true }
}, {timestamps: true});
export default mongoose.model('User', userSchema, "UserInfo");

This model will be called during the function creation, now the main work to be done. nothing is complex, we all have to remember the steps only, one occurs after another.

#userroute
import express from 'express';
import userController from '../controllers/createController';
const router = express.Router();
router.post('/register', userController.register)
router.get('/getuser/:id', userController.getUser)
router.put('/update/:id', userController.update)
router.delete('/delete/:id', userController.delete)
export default router;

the function will be called after the controller name.

const userController = {
    async register(req, res, next){
        let userData;
        try{
            const user = new userModel({
                name: req.body.name,
                email: req.body.email,
                phone: req.body.phone
            });
            try{
                userData = await user.save();
                console.log("Registered user is", userData);
            }catch(err){
                console.log("User can not be saved in DB",err)
            }
        }catch(err){
            console.log("Error occured in register function",err);
        }
        res.json({ userData });
    }
export default userController;

in the next function, we will see, how to get the registered user details

    async getUser(req, res, next){
        try{
            const userInfo = await userModel.findOne({ _id: req.params.id });
            if(!userInfo){
                return res.json( "user not found" )
            }
            return res.json(userInfo)
        }catch(err){
            console.log("Error occurred in get user function",err);
        }
    }

here is the function to update the existing user details.

    async update(req, res, next){
        try{
            const updateUser = await userModel.findByIdAndUpdate({ _id: req.params.id },{
                $set: {
                    "name":req.body.name,
                    "email":req.body.email,
                    "phone":req.body.phone
                }   
            }, { new: true });
            res.status(200).json(updateUser);
        }catch(err){
            console.log("error occurs in update function", err);
        }
    }

now last but not least, the function is to delete existing data from MongoDB.

    async delete(req, res, next){
        try{
            const dropUser = await userModel.findByIdAndRemove({ _id: req.params.id  })
            res.json(dropUser).status(200)
        }catch(err){
            console.log("Error occurs in delete function", err)
        }
    }