How to Setup MERN (MongoDB, Express JS, React JS, and Node JS) Development environment and create your first MERN stack application

How to Setup MERN (MongoDB, Express JS, React JS, and Node JS) Development environment and create your first MERN stack application


Nodejs Install 

https://nodejs.org/en/download

Mongodb Install and setup online and localhost both

Mongodb atlas online setup database

https://www.mongodb.com/atlas/database

Download Mongodb into window system

https://www.mongodb.com/try/download/community  


Setup Backend and Frontend 

  1. Create folder for backend and frontend
  2. npm init -y
  3. "type": "module"

Install package for backend

Mongoose and expressjs

npm install express mongoose --save

Create file for database db.js

import mongoose from 'mongoose'

const connectDB = async () => {
    try {
        //database Name
        const databaseName='demomern';
        const con = await mongoose.connect(`mongodb://127.0.0.1:27017/${databaseName}`, { 
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true
    });
        console.log(`Database connected : ${con.connection.host}`)
    } catch (error) {
        console.error(`Error: ${error.message}`)
        process.exit(1)
    }
}

export default connectDB

Create file server.js and import database configuration

import connectDB from './backend/config/db.js'

connectDB()

Create model directory and create datamodel.js

import mongoose from 'mongoose'

const userSchema = mongoose.Schema({
    firstName: {
        type: String,
    },
    secondName:{
        type: String,
    },
    userName: {
        type: String,
        required: true,
        unique:true
    },
    email: {
        type: String,
        required: true,
        unique:true
    },
    password: {
        type: String,
        required: true
    },
    isAdmin: {
        type: Boolean,
        required: true,
        defualt: false
    },
}, {
    timestamps: true
})

const User = mongoose.model('User', userSchema)

export default User

Create json dummy data to store on database 

[{
"_id": {
"$oid": "5fd21021d230812954b4b49a"
},
"firstName": "Manish",
"lastName": "Mandal",
"userName": "Manntrix",
"email": "admin@gmail.com",
"password": "asdfg123",
"isAdmin": true
},{
"_id": {
"$oid": "5fd21f60d230812954b4b49b"
},
"firstName": "John",
"lastName": "Doe",
"userName": "Johndoe",
"email": "johndoe@gmail.com",
"password": "asdfg123"
},{
"_id": {
"$oid": "5fd21f82d230812954b4b49c"
},
"firstName": "Demo",
"lastName": "test",
"userName": "Demo",
"email": "demo@gmail.com",
"password": "asdfg123"
}]

Create controller folder in backend and usercontroler.js file create

import User from '../models/usersModel.js'
import asyncHandler from 'express-async-handler'

//getUsers function to get all users
export const getUsers = asyncHandler(async(req, res) => {
    const users = await User.find({})
    res.json(users)
})

//getUserById function to retrieve user by id
export const getUserById  = asyncHandler(async(req, res) => {
    const user = await User.findById(req.params.id)

    //if user id match param id send user else throw error
    if(user){
        res.json(user)
    }else{
        res.status(404).json({message: "User not found"})
        res.status(404)
        throw new Error('User not found')
    }
})

Create route folder and into create routeuser.js

import { getUsers, getUserById } from "../controllers/userController.js";
import express from 'express'
const router = express.Router()


// express router method to create route for getting all users
router.route('/').get(getUsers)

// express router method to create route for getting users by id
router.route('/:id').get(getUserById)

export default router

Install

npm i dotenv --save

Import

import dotenv  from 'dotenv'dotenv.config()

Create .env file in root folder

NODE_ENV = development
PORT = 5000

Create server.js in root folder 

import connectDB from './backend/config/db.js'
import userRoutes from './backend/routes/userRoute.js'
import express from 'express'
import dotenv  from 'dotenv'

//connect database
connectDB()

//dotenv config
dotenv.config()

const app = express()

//Creating API for user
app.use('/api/users', userRoutes)

const PORT = process.env.PORT || 5000

//Express js listen method to run project on http://localhost:5000
app.listen(PORT, console.log(`App is running in ${process.env.NODE_ENV} mode on port ${PORT}`))

Install

npm i nodemon --save-dev

Now add this line under the scripts object inside the package.json file.

"start": "nodemon backend/server.js"

17. Create a react project with the name frontend.

npx create-react-app frontend

18. Install Axios into your react application.

npm install axios --save

19. Now replace all the code from the app.js file with the below-mentioned code.

import React, {useEffect, useState} from 'react'
import axios from 'axios'

const App = () => {
  const [users, setUsers] = useState([])
  const getData = async() => {
    const res = await axios.get('/api/users')
    setUsers(res.data)
  }

  useEffect(() => {
    getData()
  }, [])
 
  return (
    <div>
      {users.map(u => <h4 key={u._id}>userName : {u.userName}</h4>)}
    </div>
  )
}

export default App

Before starting our react application add the below line inside the package.json file of the react project or else you will receive a CORS error in your project.

"proxy": "http://127.0.0.1:5000",

20. Now start the application npm start and refresh the browser to see changes.

So now we have successfully built our first MERN project.



No comments:

Post a Comment