Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Prerequisites
3.
Getting Started with Project
4.
Using Node
5.
Using Express
6.
CRUD
6.1.
CREATE
6.2.
READ
6.3.
UPDATE
6.4.
DELETE
7.
Frequently Asked Questions
7.1.
What are the four CRUD components?
7.2.
What do Express' CRUD operations entail?
7.3.
What are the benefits of using Express?
7.4.
What is the substitute for Express?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

CRUD in Express

Author Nidhi Kumari
0 upvote

Introduction

The terms CRUD and Express are difficult for someone who has never done server-side programming. Before starting with the article, let's define what they are. 

Create, Read, Update, and Delete operations are referred to as CRUD, and the most widely used Node web framework is Express.

CRUD in Express

 Express streamlines the simple Node.js server creation process. It serves as the basic library for several other well-known Node web frameworks.

Now let’s discuss how to develop CRUD in Express.

Prerequisites

To start our CRUD in Express project, we first need to install Node. Open your command prompt and enter the following command to see if Node is installed in your system or not:

$ node -v

 

You will get the version of the node after execution of the above command. If you don’t have installed Node, you can install it using the Nodejs website.

You can also use some package managers to download it.

Getting Started with Project

You can start your CRUD in Express project by creating a folder for the project. After creating a folder and navigating it, run the following command:

$ npm init

 

You can manage the dependencies we'll install later in this project by creating a package.json file.

Using Node

To use Node, follow the given steps:

Step 1: The first step is to run the following command to use with node and create a file called server.js. It is the simplest way to run Node.

$ touch server.js

 

Step 2: You can use any console statement with this command to check whether your node is working correctly or not. 

For example, you can write the following message to check the working of node.

console.log('It is Working.')

 

Step 3: You need to run your server.js. You should see something like this:

It is Working.

 

Here is the complete code to create a server.js file.

var express = require('express');
//configuring properties
var properties = require('./config/properties');
//configuring database
var database = require('./config/database');
var app = express();


// calling the database connectivity function
database();


app.listen(properties.PORT, (req, res) => {
    console.log(`Your server is running on ${properties.PORT} port.`);
})

 

Note: There will be a separate properties.js file and a database connectivity file.

Now, let’s see how to use express.

Using Express

To use Express, follow the following steps:

Step 1: The first step is to install Express. By using the npm install command, we are able to do this.

Step 2: Run the following command in your command line:

$ npm install express --save

 

Here the --save flag is used to save the express as a dependency in your package.json.

Step 3: The next step is to employ express in the server.js by requiring it. Here is the code:

const express = require('express')
const app = express()

 

Step 4: Now, we will use Express’s listen method. It is used to create a server that browsers can connect.

app.listen(3000, function () {
  console.log('Server is listening at 3000 port number.')
})

 

Step 5: The final step is to launch node server.js and direct your browser to localhost:3000.

CRUD

Let’s first discuss CRUD in detail. It is a group of operations (POST, GET, PUT, and DELETE) that we ask servers to carry out. The description of each operation is as follows:

  • Create(POST): This operation is used to create something.
     
  • Read(GET): This operation picks up an object.
     
  • Update(PUT): This operation makes changes in the specified object.
     
  • Delete(DELETE): It is used to remove something.

 

Here we will use Postman to handle all our requests. Follow the given steps to use Postman.

Step 1: Download the Postman app.

Step 2: Select the "Create a request" option.

Step 3: We will create a new request for each new API endpoint we create. 

CREATE

The <form> element or JS can be used to start a POST request. The browser performs the CREATE operation only after a POST request is made to the server.

Before proceeding, you must first construct the <form> element and include it in your index.html file. Three attributes must be present in this form element. All form's "input" components include an action attribute, a method attribute, and a name attribute.

Here is the code for including all three elements:

<form action="/quotes" method="POST">
  <input type="text" placeholder="name" name="name" />
  <input type="text" placeholder="quote" name="statement" />
  <button type="submit">Submit</button>
</form>

 

Output:

Output

 

To handle this POST request at the server, we need the post method of Express.

Setting up a post request to '/quote' will include creating a new name object using our model and passing the Postman request data.

Here is the complete code:

router.get('/quotes', function (req, res) {
    const newObject = new ObjectModel({
        Name: Yoda,
        Quote: "Fear is the path to the dark side."
    });


    newObject.save(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send("Data insertion successful.");
        }
    });
});

 

We can insert as many details as we need by switching the request from GET to POST and utilising the body-parser middleware to accept the data. To do so see the following code:

router.post('/quotes', function (req, res) {
    const newObject = new ObjectModel();
newObject.Name = req.body.Name;
newObject.Quote = req.body.Quote;


 newObject.save(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send("Data insertion successful.");
        }
    });
});

READ

Every time you view a webpage, browsers carry out the READ operation. Browsers secretly submit a GET request to the server for a READ operation.

Express's get method is used to respond to GET requests. The syntax is as follows:

app.get(path/endpoint, callback)

 

path: path denotes the GET request's path. Anything that follows your domain name constitutes it. It is also known as the endpoint.
For example, you are reading this article on https://www.codingninjas.com/studio/library/crud-in-express. The domain name is codingninjas.com. So the requested path or endpoint is anything after the domain, i.e., Coding Ninjas Studio/library/crud-in-express.

 

callback: A callback function that instructs the server what to do when the path matches is provided as the second argument. Here is the syntax; a request object and a response object are its two required arguments.

app.get('/', function (request, response) {  // do something})

 

We will use the find function to get the data. Here is the complete code.

router.get('/findall', function (req, res) {
    ObjectModel.find(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send(data);
        }
    });
});

UPDATE

To find the right item, we'll use the _name. The target's name and the request data you wish to replace it with are passed to the findByNameAndUpdate() function. Here is the complete code.

router.post('/update', function (req, res) {
    ObjectModel.findByNameAndUpdate(req.body.name,
        { Name: req.body.Name }, 
function (err, data) {
            if (err) {
                console.log(error);
            }
            else {
                res.send(data);
                console.log("Your entered data is updated!");
            }
        });

DELETE

You need to utilise the remove() function to remove a record from the database. Here is the code that explains how to apply the delete operation in your database.

router.get('/delete', function (request, response) {
    ObjectModel.remove({ Name: Yoda },
        function (err, data) {
            if (err) {
                console.log(error);
            }
            else {
                res.send(data);
            }
        });
});

 

Like the update operation, you can also use the findByNameAndDelete() function to delete the data easily.

Frequently Asked Questions

What are the four CRUD components?

The terms CREATE, READ, UPDATE, and DELETE are abbreviated as CRUD. It is a group of operations (POST, GET, PUT, and DELETE) that we ask servers to carry out. These terms refer to the four fundamental procedures for establishing and controlling permanent data components.

What do Express' CRUD operations entail?

The operations CRUD (Create, Read, Update, Delete) let you interact with the data stored within DataBase. Two sections comprise the CRUD operation documentation:  Read, write, post, and get operations respectively.

What are the benefits of using Express?

Express is simple to set up and customise. It includes numerous middleware modules that you can use to add to request and response operations. It enables you to create application routes based on URLs and HTTP methods.

What is the substitute for Express?

You can use NextJs as an alternative to Express. In both client-side and server-side applications, NestJS is intended for use. For creating effective and scalable server-side applications, NestJS is a full-stack JavaScript framework. 

Conclusion

In this article, we extensively discussed CRUD in Express. The operations CRUD (Create, Read, Update, Delete) let you interact with the data stored within DataBase. Using CRUD in Express, you can set up a simple app.

We hope this article helps you. You can visit more articles.

 

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Reading!!

Live masterclass