CRUD application using MERN Stack

Shivam
GDSC GHRCE
Published in
6 min readJun 15, 2021

In this tutorial, we will be creating a CRUD application from scratch by using Node.js, Express, and MongoDB under the MERN stack. CRUD , this term stands for create, read ,update and delete and this can be achieved by creating Rest APIs named POST, GET, PUT and DELETE respectively.

MERN is an acronym for MongoDB, Express, React, and Node. In this tutorial, we will be focusing on the back-end part so we won't be using React.

Node.js: It is an asynchronous event-driven Javascript runtime environment built on Google Chrome’s V8 engine designed to build scalable network applications.

Express: It is a minimal and flexible Node.js web application framework that helps in developing Rest APIs released as free open-source software under MIT license.

MongoDB: It is a document-based database built for modern application developers which stores data in JSON-like documents.

We will be creating a simple ToDo app where we will be able to add the tasks, read the tasks, update the tasks and delete the tasks.

Creating Application:

Firstly check whether Node is installed on your device, run the code in your Command Line.

node -v

If Node is installed in your system you will get the version of the installed Node else you can directly download it from their website using their installer.

After installing Node, create a folder and open it using the terminal. For initiating the project you need to install some basic packages by using the npm feature for creating a package.json file. Run the following command for initiating the package.json file which will help you to manage dependencies.

npm init

You will get various fields to input such as package name, version, entry point, author, and more, just hit enter through everything that appears. The package.json file will be created.

After this, we need to install other packages which we will be using like Express, MongoDB, mongoose, nodemon . We now know what express and MongoDB are, but we don’t much about mongoose and nodemon.

npm install express
npm install mongodb

Mongoose is an Object Data Modeling(ODM) library for MongoDB and Node.js.

npm install mongoose

When you will be working on this project you as a developer will make multiple changes and for these changes to reflect on your server, you need to restart your server, to automate this thing you need to install nodemon. We will install nodemon as devDependencies.

npm install nodemon --save-dev

After you install the packages you can verify it in the dependencies section under the package.json file, also there will be a node_modules file that will contain all the modules of the packages installed.

For the nodemon to work you need to update the scripts in the package.json file.

"scripts": {
"start":"nodemon app.js"
}

This is how your package.json file will look after completing the above steps.

package.json

Now we will create the main file of the project app.js. Since we are going to use express and mongoose here, we will first require them in our file. We will then connect the MongoDB database to our application using mongoose then create a call-back function to check the connection of the database to our application and finally, we will have a call-back to check whether our server is running or not.

const express = require("express");
const app= express()
//Connecting the database
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/ToDo',
{useNewUrlParser: true})
.then(()=>{
console.log("DB connected")
})
//Listening to the server
app.listen(5000,()=>{
console.log("Server is listening on port 5000")
})

After connecting the database to the application we need to define the database model. So we will create another file named user.js. After navigating to this file we will require mongoose here and use its functionality of schema to define the user schema with properties name, status, task. At last, we will finally export the schema so that it can be used in other files.

const mongoose = require("mongoose")//Defining Schema
const userSchema = new mongoose.Schema({
name:{
type:String,
required:true,
trim:true,
maxlength:32
},
task:{
type:String,
required:true,
trim:true
},
status:{
type:Boolean,
default:0
}
},
{ timestamps: true }
)
//Exporting the schema
module.exports = mongoose.model("User",userSchema)

You can visualize the database using Robo 3T tool, you just need to install it using their official website. Fire the application and click on create and add a name to the connection and leave the address to default 27017 as we have connected our database to the application using the same address.

Robo 3T new connection

Now to manage different functionalities we need to include routing in our project for which we will open the app.js file and add a route “/users” which whenever invoked will require everything exported from the users.js file.

//add this to app.js file
const userRouter = require("./routes/users")
app.use("/users",userRouter)

Now create a route file named users.js and require express, router, and model we exported from the user.js file. We will create here different routes for adding a task, deleting a task, updating a task, and getting tasks. Navigate to the users.js file and enter these codes.

// requiring express,router and models
const express = require("express");
const router = express.Router();
const User= require("../models/user")

Adding Task:

We will create a POST route “/addtask” to add a new task. We will input names, tasks, and statuses and save them in the database. To create a post route follow the following code.

//adding the post routerouter.post("/addtask",async(req,res)=>{
const user =new User({
name:req.body.name,
task:req.body.task,
status:req.body.status
})
try{
const u1= await user.save()
res.json(u1)
}
catch(err){
res.send("error"+ err)
}
})

Reading Task:

After the POST route, we will create a GET route to read the tasks stored. We will create two types of GET route, one which will read all tasks at once and the other which will read tasks by their id. The code for the above is

//GET route to read all the tasks
router.get("/get",async(req,res)=>{
try{
const users= await User.find()
res.json(users)
}
catch(err){
res.send("ERROR"+ err)
}
})
//GET route to recieve task by id
router.get("/get/:id",async(req,res)=>{
try{
const user= await User.findById(req.params.id)
res.json(user)
}
catch(err){
res.send("ERROR"+ err)
}
})

Updating Task:

To update the task we will create a put route “/update/:id” . This will update the information in the database according to their id. The code for this route is

//PUT route to update information
router.put("/update/:id",async(req,res)=>{
try{
const user= await User.findById(req.params.id)
user.name=req.body.name
user.task=req.body.task
user.status=req.body.status
const a1 = await user.save()
res.json(a1)
}
catch(err){
res.send("Error")
}
})

Deleting Task:

We then create a delete route that deletes the user information according to their id. The route created is “delete/:id”. The code for the above route is

//DELETE route to delete user information
router.delete("/delete/:id",async(req,res)=>{
try{
const user= await User.findById(req.params.id)
user.name=req.body.name
user.task=req.body.task
user.status=req.body.status
const u1 = await user.delete()
res.json(u1)
}
catch(err){
res.send("Error"+err)
}
})

After creating all the routes in the users.js file add a single code to export this information so that it can be used in the app.js file.

module.exports=router

We can check our APIs using the Postman application which can be downloaded from its website and used easily. Refer to this documentation to understand how to use it.

Adding task:

adding task

Getting all task:

getting all tasks
get task by id

Update Task:

update task by id

Delete Task:

delete task by id

Along with testing the APIs, you can visualize your database on Robo 3T, and this is how your database will look like.

Robo 3T

Wrapping up, I hope you understood the MERN stack, Express, MongoDB, and Node. This tutorial also helped you to understand the basics of Postman and Robo 3T. It also covered the CRUD and Rest APIs. I hope you all enjoyed reading this article, for any bugs and queries feel free to connect with me.

--

--

Shivam
GDSC GHRCE

BTech in Artificial Intelligence |Core team member at DSC GHRCE