CRUD in Express
Overview
In this article, we are going to learn about CRUD in the express. Before getting started with the topic, let us get a short overview of the topic.
CRUD in Express: CRUD in ExpressJS refers to the four basic operations of persistent storage: Create, Read, Update, and Delete. These operations are essential in building web applications that interact with a database or any other data source. With ExpressJS, developers can easily implement CRUD functionality by defining routes that handle each operation and interact with the database through an ORM or other data access library. The framework provides a flexible and scalable architecture for building web applications that can handle a high volume of traffic and provide a seamless user experience.
So let us now begin with the main agenda of our article, CRUD in Express.
Introduction
ExpressJS is a popular Node.js framework that provides a set of powerful tools for building web applications, including support for handling HTTP requests and responses, routing, middleware, and more. The framework provides a flexible and scalable architecture for building web applications that can handle a high volume of traffic and provide a seamless user experience. In Express JS, CRUD refers to the four basic operations that can be performed on a database or resource - Create, Read, Update, and Delete.
What is CRUD in Express JS?
ExpressJS is a popular open-source web application framework that allows developers to easily implement CRUD (Create, Read, Update, and Delete) functionality in web applications.
Due to the powerful routing system and middleware support of expressJS, developers can define routes to handle each CRUD operation and interact with the database or any other data source through an ORM or data access library. For example, the framework provides built-in methods such as app. get(), app. post(), app. put(), and app. delete() to handle HTTP requests for reading, creating, updating, and deleting data respectively. These methods can be used to define routes that map to specific CRUD operations, making it easy to build RESTful APIs and web applications that interact with a database or other data sources. With its flexibility, scalability, and ease of use, ExpressJS is an excellent choice for developers who want to implement CRUD functionality in their web applications. These operations correspond to the HTTP methods of POST, GET, PUT/PATCH, and DELETE respectively.
Here's a brief overview of what each operation does:
Create (POST): This operation is used to create a new resource in the database. In Express, you can use the app. post() method to handle POST requests.
Read (GET): This operation is used to retrieve data from the database. In Express, you can use the app. get() method to handle GET requests.
Update (PUT/PATCH): This operation is used to modify an existing resource in the database. In Express, you can use the app. put() or app. patch() method to handle PUT/PATCH requests.
Delete (DELETE): This operation is used to remove a resource from the database. In Express, you can use the app. delete() method to handle DELETE requests.
By implementing these operations in your Express application, you can perform basic database operations and create a RESTful API that can be consumed by clients.
What are the CRUD Operations?
The CRUD operations are a set of four fundamental operations that can be carried out on persistent storage systems like databases. These operations are named Create, Read, Update, and Delete, and they are widely used in web development to manage user-generated data. They align with the HTTP methods of POST, GET,** PUT/PATCH**, and DELETE, respectively. Here is a detailed explanation of each operation with examples:
Create (POST)
To insert new data into a database, we use the Create operation. In RESTful API, this operation is often accomplished using the POST method. For instance, let's consider a scenario where you have a user database and would like to include a new user. By using the POST method, you can submit the user's details to the server, which can add the data to the database. Here's an example of a POST request used to create a new user within a RESTful API in ExpressJS:
Explanation
In this example, we define a route that handles POST requests to create a new user at the endpoint /users. When a POST request is received, we extract the data from the request body using the req. body object. We then perform some validation on the data to make sure that all the required fields (name, email, and password) are present. If any of the fields are missing, we send a 400 Bad Request response with an error message.
If the validation passes, we create a new user object with the provided data, assign it an ID (in this case, we hardcode it as 1), and save it to the database (again, this is just an example and not a real database!). Finally, we send a 201 Created response with the new user object in the response body.
Note that this is just one example of how you can implement the Create operation in ExpressJS. The actual implementation may vary depending on your specific use case and the database technology you are using.
Read (GET)
To obtain data from a database, we use the Read operation. In RESTful API, this operation is commonly implemented using the GET method. For instance, let's imagine you have a user database and want to acquire a list of all the users in the database. By utilizing the GET method, you can retrieve the user data from the server. Here's an example of a GET request used to retrieve all users within a RESTful API:
Explanation
In this example, we define a route that handles GET requests to retrieve a user by ID at the endpoint /users/:id. When a GET request is received, we extract the user ID from the request parameters using the req. params object. We then retrieve the user with the provided ID from the database (again, this is just an example and not a real database!). If no user is found with the provided ID, we send a 404 Not Found response with an error message.
If a user is found, we send a 201 created JSON response with the user object in the response body.
Update (PUT / PATCH)
The operation of updating existing data in a database is referred to as the Update operation. In a RESTful API, the Update operation can be implemented using either the PUT or PATCH methods. The main difference between the two methods is that if we are using the PUT method, we have to provide the entire resource in the payload and it will modify the entire data, whereas, in the case of the PATCH method, it is not necessary to provide the entire resources, and we are just required to provide those fields in the payload which we want to update, and it will modify only those specific fields.
For instance, suppose you have a database of products, and you want to update the price of a specific product. You can use either the PUT or PATCH method to send the updated information to the server, which will then modify the product's price in the database. Here's an example of a PUT request to update the price of a product in a RESTful API:
Explanation
In this example, we define a route that handles PUT requests at the endpoint /products/:id to update the price of a product with a specific ID. We first use the find method to search for the product in the products array by its ID, which is passed in the request URL as a parameter. If the product is not found, we return a 404 error response. Otherwise, we update the product's price with the new price from the request body and return the updated product object in the response with the status code of 200 (Success).
To test this route, we can use a tool like Postman to send a PUT request to http://localhost:3000/products/2 with the following JSON payload:
This will update the price of the product with ID 2 to 24.99 and return the updated product object in the response:
Here's an example of how you can update data in ExpressJS using the PATCH method:
Explanation
In this example, we define a route that handles PATCH requests to update the price of a product with a specific ID. We first use the find method to search for the product in the products array by its ID, which is passed in the request URL as a parameter. If the product is not found, we return a 404 error response.
Otherwise, we update the product's price with the new price from the request body, but only if the price property is present in the request body. This is because the PATCH method is typically used to make partial updates, so we only update the properties that are specified in the request body.
We then return the updated product object in the response.
To test this route, we can use a tool like Postman to send a PATCH request to http://localhost:3000/products/2 with the following JSON payload:
This will update the price of the product with ID 2 to 24.99 and return the updated product object in the response:
Remove (DELETE)
The operation of deleting existing data from a database is referred to as the Remove operation. In a RESTful API, the Remove operation can be implemented using the DELETE method. For instance, suppose you have a database of products, and you want to delete any specific product. You can use the DELETE method to send the request to the server, which will then delete the particular product from the database. Here's an example of a DELETE request to remove a particular product from the database in a RESTful API:
Explanation
This example demonstrates how to handle DELETE requests in an ExpressJS server. The server defines a route for handling DELETE requests at the path /products/:id, where the URL parameter :id represents the id of the product to be deleted. Upon receiving a DELETE request at this URL, the server extracts the id parameter from the request using the req.params.id property.
Using this id, the server searches for the corresponding product in the products array using the findIndex method. If the product is found, it is removed from the products array using the splice method and returns a status code of 204 (No Content status code) which describes that the product is successfully removed from the products array.
In case the product with the specified id is not found, the server sends a 404 Not Found status code along with an error message.
In summary, the DELETE method allows you to delete a specific item from a database, and the example illustrates how to handle DELETE requests in ExpressJS, extract URL parameters, and remove items from an array.
Building a Simple CRUD-Based Application Using Express JS
Let us now build a simple CRUD-based application using Express JS.
Step 1: Setting up the environment Before we can start building the application, we need to make sure that we have a working environment set up. This includes installing Node.js and Express JS.
To install Node.js, visit the official website at Install NodeJS and follow the installation instructions for your operating system.
To install Express JS, open your terminal and type the following command:
Step 2: Creating the project folder Once we have set up the environment, we can create a new project folder for our application. Open your terminal and navigate to the directory where you want to create the project folder. Then, type the following command:
This will create a new folder called "my project".
Step 3: Creating the server Next, we need to create the server using Express JS. Create a new file called "server.js" in your project folder and add the following code:
This code imports the Express JS module, creates a new instance of the application, sets up a route for the root URL /, and starts the server listening on port 3000. The response sends the message Hello World!.
To run the server, open your terminal and navigate to the project folder. Then, type the following command:
This will start the server, and you should see the message "Server started on port 3000" in your terminal.
Step 4: Creating the database To store our data, we need to create a database. For this example, we will use MongoDB, a popular NoSQL database.
To install MongoDB, visit the official website at Install MongoDB and follow the installation instructions for your operating system.
Once you have installed MongoDB, you can start the database by typing the following command in your terminal:
This will start the MongoDB server, and you should see the message waiting for connections on port 27017 in your terminal.
Step 5: Connecting to the database Now that we have created the database, we need to connect to it from our Express JS application.
Add the following code to your server.js file, just before the app.listen() method:
Step 6: Defining the data model To interact with the database, we need to define the data model for our application. In this example, we will create a simple model for a "Task" with a title and a description.
Create a new file called "task.js" in your project folder and add the following code:
This code defines a new Mongoose schema for a Task, with a title and a description. The title and description fields are both required strings.
The last line creates a new Mongoose model for a Task, based on the taskSchema, and exports it so that it can be used in other files.
Step 7: Creating routes for CRUD operations Now that we have defined our data model, we can create routes for performing CRUD operations on our tasks.
Create a new file called "routes.js" in your project folder and add the following code:
Explanation
In the above code, The express package is imported, along with the Router class, and the Task model is imported from a separate task.js file.
A new instance of the Router is created and assigned to the router constant. This router instance will be used to define the routes for handling CRUD operations.
The router instance defines the following routes:
GET /tasks: This route returns a list of all tasks. It uses the Task model's find() method to retrieve all tasks from the database. If successful, the route sends the retrieved tasks in JSON format to the client. If an error occurs, a 500 status code and an error message are returned.
GET /tasks/:id: This route returns a single task with the specified ID. It uses the getTask middleware function to retrieve the task with the specified ID. If successful, the route sends the retrieved task in JSON format to the client.
POST /tasks: This route creates a new task. It uses the Task model to create a new task instance with the specified title and description properties. If successful, the route sends a 201 status code and the new task in JSON format to the client. If an error occurs, a 400 status code and an error message are returned.
PATCH /tasks/:id: This route updates an existing task with the specified ID. It uses the getTask middleware function to retrieve the task with the specified ID and updates its title and description properties with the values provided in the request body if they are not null. If successful, the route sends the updated task in JSON format to the client. If an error occurs, a 400 status code and an error message are returned.
PUT /tasks/:id: This handler will update the title and description of the task with the specified ID, using the data in the request body. It first checks that the request body contains both a title and a description and returns a 400 Bad Request status code if not. Otherwise, it updates the task and sends the updated task data as a response.
Note that the PUT method differs from the PATCH method in that it requires the entire resource to be sent in the request body, whereas the PATCH method only requires the updated fields to be sent. Therefore, the PUT method in this example updates both the title and description fields, whereas the PATCH method only updates the fields that are present in the request body.
DELETE /tasks/:id: This route deletes an existing task with the specified ID. It uses the getTask middleware function to retrieve the task with the specified ID and removes it from the database using the remove() method. If successful, the route sends a message confirming the deletion of the task to the client. If an error occurs, a 500 status code and an error message are returned.
The getTask function is defined outside the router instance. It is an asynchronous function that retrieves a task from the database with the specified ID and attaches it to the res object. If the task is not found, a 404 status code and an error message are returned. If an error occurs, a 500 status code and an error message are returned.
Finally, the router instance is exported so that it can be used in the main app.js file to handle requests for CRUD operations on tasks.
Step 9: Testing the application To test the application, start the server by running the following command:
Then use a tool like Postman to send HTTP requests to the server and verify that the CRUD operations are working as expected.
For example, to create a new task, send a POST request to http://localhost:3000/api/tasks with a JSON payload like this:
To retrieve all tasks, send a GET request to http://localhost:3000/api/tasks.
To retrieve a specific task, send a GET request to http://localhost:3000/api/tasks/:id, where ": id" is the ID of the task you want to retrieve.
To update a task, send a PATCH request to http://localhost:3000/api/tasks/:id with a JSON payload containing the fields you want to update.
To delete a task, send a DELETE request to http://localhost:3000/api/tasks/:id.
Congratulations, you have now built a simple CRUD-based application using Express.js!
Conclusion
In this article, we learned about CRUD in expressJS. Let us recap the points we discussed throughout the article:
- ExpressJS is a popular Node.js framework that provides a set of powerful tools for building web applications, including support for handling HTTP requests and responses, routing, middleware, and more.
- CRUD in ExpressJS refers to the four basic operations of persistent storage: Create, Read, Update, and Delete.
- With ExpressJS, developers can easily implement CRUD functionality by defining routes that handle each operation and interact with the database through an ORM or other data access library.
- the ExpressJS framework provides built-in methods such as app. get(), app. post(), app. put(), and app. delete() to handle HTTP requests for reading, creating, updating, and deleting data respectively.
- These methods can be used to define routes that map to specific CRUD operations, making it easy to build RESTful APIs and web applications that interact with a database or other data sources.
- Create (POST) operation is used to create a new resource in the database. In Express, you can use the app. post() method to handle POST requests.
- Read (GET) operation is used to retrieve data from the database. In Express, you can use the app. get() method to handle GET requests.
- Update (PUT/PATCH) operation is used to modify an existing resource in the database. In Express, you can use the app. put() or app. patch() method to handle PUT/PATCH requests.
- The main difference between PUT and PATCH methods is that if we are using the PUT method, we have to provide the entire resource in the payload and it will modify the entire data, whereas, in the case of the PATCH method, it is not necessary to provide the entire resources, and we are just required to provide those fields in the payload which we want to update, and it will modify only those specific fields.
- Delete (DELETE) operation is used to remove a resource from the database. In Express, you can use the app. delete() method to handle DELETE requests.
- Then we have also built a simple CRUD-based application using Express JS.