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.
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:
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:
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:
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.