Create a MERN CRUD Application Part 1

1 year ago admin Nodejs

In this tutorial, we will see how to create a MERN crud application, the application is a task manager where the user can add update, and delete tasks, in the first part we will handle the backend, and in the second part, we will handle the frontend.


Create the database

So, let's handle the backend first create the project folder and name it as you want inside add a new folder give it 'backend' as the name and inside run the command:

npm init

Next, let's install the packages we need:

npm install express mongoose cors nodemon

Next, let's update the 'package.json' file we set the type to 'module' and add the script 'dev':

Demo
Next, to create the database you need to have a MongoDB account after you create your account follow the images to create the database:

Finally, create a new file 'config.js' inside the backend folder add the copied link inside, and change the user to your username and the password to your password.

                                                    
                                                                                                                
export const db = "mongodb+srv://user:password@mern.hbwnmcq.mongodb.net/tasks?retryWrites=true&w=majority";

Create the taskModel

Inside the backend folder create a new folder 'models' inside create a new file 'taskModel.js' and add the code below inside.

                                                        
                                                                                                                        
import mongoose from "mongoose";

const taskSchema = mongoose.Schema(
    {
        title: {
            type: String,
            required: true,
        },
        description: {
            type: String,
            required: true
        },
        done: {
           type: Boolean,
           default: 0,
           required: false 
        }
    },{
        timestamps: true
    }
);

const Task = mongoose.model('Task', taskSchema);

export default Task;

Create routes

Inside the backend folder create a new folder 'routes' inside create a new file 'taskRoutes.js' and add the code below inside.

                                                        
                                                                                                                        
import express from 'express';
import Task from '../models/taskModel.js';

const taskRouter = express.Router();

taskRouter.post('/', async (req, res) => {
    try {
        if(!req.body.title || !req.body.description) {
            return res.status(422).send({
                message: 'All the fields are required!'
            });
        }
        const newTask = {
            title: req.body.title,
            description: req.body.description
        };
        const task = await Task.create(newTask);
        return res.status(200).send(task);
    } catch (error) {
        console.log(error);
        return res.status(500).send({
            message: error.message
        });
    }   
});


taskRouter.get('/', async (req, res) => {
    try {
        const tasks = await Task.find({});
        return res.status(200).send({tasks});
    } catch (error) {
        console.log(error);
        return res.status(500).send({
            message: error.message
        });
    }
});


taskRouter.get('/:id', async(req, res) => {
    try {
        const { id } = req.params;
        if(!id.match(/^[0-9a-fA-F]{24}$/)) {
            return res.status(500).send({
                message: "The provided id is not valid!"
            });
        }
        const task = await Task.findById(id);
        return res.status(200).send({task});
    } catch (error) {
        console.log(error);
        return res.status(500).send({
            message: error.message
        });
    }
});

taskRouter.put('/:id', async(req, res) => {
    try {
        const { id } = req.params;
        if(!req.body.title || !req.body.description) {
            return res.status(422).send({
                message: 'All the fields are required!'
            });
        }
        if(!id.match(/^[0-9a-fA-F]{24}$/)) {
            return res.status(500).send({
                message: "The provided id is not valid!"
            });
        }
        const result = await Task.findByIdAndUpdate(id, req.body);
        if(!result) {
            return res.status(500).send({
                message: "Task not found"
            });
        }
        return res.status(200).send({message: 'Task updated successfully!'});
    } catch (error) {
        console.log(error);
        return res.status(500).send({
            message: error.message
        });
    }
});

taskRouter.delete('/:id', async(req, res) => {
    try {
        const { id } = req.params;
        if(!id.match(/^[0-9a-fA-F]{24}$/)) {
            return res.status(500).send({
                message: "The provided id is not valid!"
            });
        }
        const result = await Task.findByIdAndDelete(id);
        if(!result) {
            return res.status(500).send({
                message: "Task not found"
            });
        }
        return res.status(200).send({message: 'Task deleted successfully!'});
    } catch (error) {
        console.log(error);
        return res.status(500).send({
            message: error.message
        });
    }
});

export default taskRouter;

Create the index file

Inside the backend folder create a new file 'index.js' and add the code below inside.

                                                        
                                                                                                                        
import { db } from "./config.js";
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import taskRouter from './routes/taskRoutes.js';

const app = express();
app.use(express.json());

app.use(cors());

app.use('/tasks', taskRouter);


//connect to the database
mongoose.connect(db).then(() => {
    app.listen(3001, () => {
        console.log('App is running on port 3001');
    });
}).catch(error => console.log(error));