How to create Simple Crud Operation using MERN System Project

Creating CRUD (Create, Read, Update, Delete) modules is a fundamental part of developing any web application. In this tutorial, we will explore how to create a simple CRUD operation module in a MERN (MongoDB, Express, React, Node.js) system. Before we begin, make sure you have the following installed:

– Node.js
– NPM
– MongoDB

Let’s start by creating a new project. Open your terminal and enter the following commands:

“`bash
mkdir mern-crud
cd mern-crud
npm init -y
“`

This will create a new directory called `mern-crud`, initialize a new NPM project, and create a `package.json` file.

Next, we need to install the required dependencies. Enter the following commands in your terminal:

“`bash
npm install express mongoose body-parser cors
npm install nodemon –save-dev
“`

Here, we are installing the following packages:

– `express`: to create a server
– `mongoose`: to connect to MongoDB
– `body-parser`: to parse incoming request bodies
– `cors`: to enable cross-origin resource sharing
– `nodemon`: to automatically restart the server on changes

Now, let’s create the server. Create a new file called `server.js` in the root directory and add the following code:

“`javascript
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);

const app = express();
const PORT = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(cors());

mongoose.connect(‘mongodb://localhost/mern-crud’, {
useNewUrlParser: true,
useUnifiedTopology: true
});

const connection = mongoose.connection;
connection.once(‘open’, () => {
console.log(‘MongoDB database connection established successfully’);
});

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
“`

Here, we are importing the required packages, creating an instance of the Express application, setting the port number, and connecting to the MongoDB database. We are also setting up the middleware for parsing incoming request bodies and enabling CORS.

To start the server, enter the following command in your terminal:

“`bash
npm run dev
“`

This will start the server using `nodemon`.

Now, let’s create the CRUD operation modules for our application. First, we need to create a `model` for our data. Create a new file called `user.model.js` in a `models` directory and add the following code:

“`javascript
const mongoose = require(‘mongoose’);

const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
}, {
timestamps: true
});

const User = mongoose.model(‘User’, userSchema);

module.exports = User;
“`

Here, we are defining the schema for our `User` model. We are requiring a `username`, `email`, and `password` field, and adding a timestamp for when the data was created. We are then creating a new instance of the `User` model and exporting it.

Next, we need to create the routes for our CRUD operations. Create a new file called `users.js` in a `routes` directory and add the following code:

“`javascript
const router = require(‘express’).Router();
let User = require(‘../models/user.model’);

router.route(‘/’).get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json(`Error: ${err}`));
});

router.route(‘/:id’).get((req, res) => {
User.findById(req.params.id)
.then(user => res.json(user))
.catch(err => res.status(400).json(`Error: ${err}`));
});

router.route(‘/add’).post((req, res) => {
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;

const newUser = new User({
username,
email,
password,
});

newUser.save()
.then(() => res.json(‘User added!’))
.catch(err => res.status(400).json(`Error: ${err}`));
});

router.route(‘/:id’).delete((req, res) => {
User.findByIdAndDelete(req.params.id)
.then(() => res.json(‘User deleted.’))
.catch(err => res.status(400).json(`

 

admin

Recent Posts

Why Is User Experience the Foundation of Successful Website Design?

A website should do more than simply look visually attractive. Modern websites must also provide smooth, intuitive, and user-friendly experiences…

7 days ago

How Can Businesses Turn Website Visitors Into Qualified Leads?

Attracting website traffic is important, but traffic alone does not guarantee business growth. The real value of a website comes…

7 days ago

What Are the Key Differences Between Cheap Websites and Professional Websites?

A business website is one of the most important tools for creating online visibility and attracting customers. Many businesses, especially…

7 days ago

How Does Website Design Affect Online Brand Reputation?

A business website is often the first interaction customers have with a company. Before contacting a business, booking a service,…

7 days ago

What Are the Benefits of Investing in Custom Web Development Services?

A business website is one of the most important digital assets in today’s competitive online environment. Many companies begin with…

7 days ago

How Can Businesses Design Websites That Convert Mobile Users Better?

Mobile users now make up a major portion of website traffic across almost every industry. Customers increasingly browse websites, search…

7 days ago