Basic Backend Project Setup with Crud Operations(MERN)

Basic Backend Project Setup with Crud Operations(MERN)

MERN SETUP || RESTful apis || CRUD operation

Hello Everyone, Today I am gonna share something which can really help you to start with your project in MERN Stack*

So Lets start with an example on which I am writing this blog

In Today's world we all use social media , right? Y'all won't believe once my average time spent per day on instagram was around 9-10hr but today we not here to discuss this . I want you all to think about the basic functionality of our social media app i.e CRUD operations

C - CREATE

R - READ

U - UPDATE

D - DELETE

Let me explain you what I am talking about

We can say that When we post a something on social media app we are performing a CREATE operation. Similarly When scroll through the feed we are performing READ operation. Same goes for other 2 operation like when edit our post we are performing UPDATE operation and when we delete a post DELETE operation is done.

Don't you think that most of the projects or webapp have this functionality whether it is a ecommerce website or messaging app or any other app.

So today we will be Basic Setup for our other projects with Crud Operations which you can use in start of any project which you will be building.

HERE WE GO

First make a folder name "setup project"

image.png

first initialize our project by running this command in terminal

npm init

then install

npm i express mongoose dotenv

in app.js

const express = require("express");
const app = express();

app.use(express.json());

module.exports = app;

here we have setup express and now we will be connecting mongodb

image.png

now make config.env and database.js

in database.js

const mongoose = require("mongoose")

const connectDatabase=()=>{
    mongoose.connect(process.env.DB_URI,{useNewUrlParser:true,useUnifiedTopology:true
    }).then((data)=>{
        console.log(`Mongodb connected with server: ${data.connection.host}`);
    }).catch((err)=>{
        console.log(err);
    })
}

module.exports=connectDatabase;

in config.env

PORT=4000
DB_URI="mongodb://localhost:27017/projectsetup"

in server.js

const app = require("./app")

const dotenv = require("dotenv")
const connectDatabase = require("./config/database")

//config
dotenv.config({path:"backend/config/config.env"});

//connecting to database
connectDatabase();


app.listen(process.env.PORT,()=>{
    console.log(`Server is working on https://localhost:${process.env.PORT}`)
})

so here we have connected our app now edit your scripts in package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"node backend/server.js",
    "dev" : "nodemon backend/server.js"
  },

image.png

Now We have completed the initial setup for backend of our project and now we will build crud apis

Let's say we are building a E-commerce website where we need to CRUD operation of Products.

So let's Continue build some apis.

First make a folder "Controllers" in that folder make a file "productController.js". Similarly make a folder "models" in that folder make a file "prodelModel.js"

image.png

First we will make a model and a schema for our product.

basically a Product schema is blueprint of our product.

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please Enter product Name"],
    trim: true,
  },
  description: {
    type: String,
    required: [true, "Please Enter product Description"],
  },
  price: {
    type: Number,
    required: [true, "Please Enter product Price"],
    maxLength: [8, "Price cannot exceed 8 characters"],
  },
});

module.exports = mongoose.model("Product", productSchema);

As you can see it is basic schema of a product in ecommerce.

Now we will make controllers for our products. Controllers contains the functions which will when a specific api is called.

const Product = require("../models/ProductModal")
//Create Product 
exports.createProducts = async(req,res,next)=>{
    const product = await Product.create(req.body);
    res.status(201).json({
        success:true,
        product
    })
}
//Get All Product
exports.getAllProducts = async(req,res)=>{

    const products  = await Product.find();
    res.status(201).json({
        success:true,
        products
    })
}
//get single product deltails
exports.getProductDetails = async(req,res,next)=>{

    const product = await Product.findById(req.params.id);
    if(!product){
        return res.status(500).json({
            success:false,
            message:"Product not found"
        })
    }
    res.status(201).json({
        success:true,
        product
    })
}
//Update any product -- Admin
exports.updateProduct = async(req,res,next)=>{
    let product =await Product.findById(req.params.id);
    if(!product){
        return res.status(500).json({
            success:false,
            message:"Product not found"
        })
    }
    product = await Product.findByIdAndUpdate(req.params.id,req.body,{
        new:true,
        runValidators:true,
        useFindAndModify:false
    })
    res.status(201).json({
        success:true,
        product
    })
}
//Delete Product
exports.deleteProduct = async(req,res,next)=>{
    const product = await Product.findById(req.params.id);
    if(!product){
        return res.status(500).json({
            success:false,
            message:"Product not found"
        })
    }
    await product.remove();
    res.status(201).json({
        success:true,
        message:"Product deleted successfully"
    })

You can see that i have made functions which use queries to perform the crud operations for our product.

Now we will connect these controllers with Routes.

make a routes folder and a file "productRoutes"

image.png

Before that let's first get to know about some HTTP request and simultaneously we will make routes too.

GET - List all blog products

POST - Add product to database

PUT - Update a particular product

DELETE - Delete a specific product

in productRoutes.js

const express = require("express");
const { getAllProducts , createProducts, updateProduct, deleteProduct, getProductDetails } = require("../controllers/productController");

const router = express.Router();

router.route("/products").get(getAllProducts)
router.route("/product/new").post(createProducts)
router.route("/product/:id").put(updateProduct).delete(deleteProduct).get(getProductDetails)

module.exports = router;

and at last we will connects the routes with our express

in app.js

const express = require("express")
const app = express()

app.use(express.json())

//Route import

const product = require("./routes/productRoute")

app.use("/api/v1",product)

module.exports = app

So here our Basic Backend Project Setup with Crud Operations(MERN) is completed. Hence for me it has helped me a lot especially in hackathons where i just use this setup for the setup as you can see this can used in most of our project which save a lot of time.

Here is the github link of my setup project

I hope this help you , Thank you so much.