{"id":2936,"date":"2022-07-20T18:12:13","date_gmt":"2022-07-20T23:12:13","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2936"},"modified":"2022-07-20T18:32:24","modified_gmt":"2022-07-20T23:32:24","slug":"complete-guide-to-build-a-crud-api-with-node-js-and-mongodb","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/","title":{"rendered":"Complete Guide to Build a CRUD API with Node.js and MongoDB"},"content":{"rendered":"\n<p>Have you ever wondered how the front end and the back end work together to form a complete full-stack application? You probably have heard the term API(Application Programming Interface).&nbsp;It is a mechanism with a functional role that facilitates the communication between the front end and the back end in a web application.<strong>&nbsp;<\/strong>API is the interface that makes the communication between the software components like the server, database, and client possible.<\/p>\n\n\n\n<p>In this in-depth article, you will learn how to build a CRUD API with Node.js and MongoDB using the Express framework.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#What_is_a_CRUD_API\" >What is a CRUD API?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#How_to_Build_a_CRUD_API_with_Nodejs_and_MongoDB\" >How to Build a CRUD API with Node.js and MongoDB<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Create_the_Project\" >Create the Project<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Install_the_Packages_and_Tools\" >Install the Packages and Tools<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_the_Express_Web_Server\" >Creating the Express Web Server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_Routes\" >Creating Routes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Connecting_the_Application_to_the_Database\" >Connecting the Application to the Database<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_a_Cluster\" >Creating a Cluster<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_Database_Account\" >Creating Database Account<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Adding_IP_Address_to_Access_List\" >Adding IP Address to Access List<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_a_Collection\" >Creating a Collection<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Connecting_the_Application_to_the_Database-2\" >Connecting the Application to the Database<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Setting_the_Database_Connection\" >Setting the Database Connection<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_Model\" >Creating Model<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Creating_Controllers\" >Creating Controllers<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#CREATE\" >CREATE<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#READ\" >READ<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#UPDATE\" >UPDATE<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#DELETE\" >DELETE<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Sending_Request_to_API_Endpoints\" >Sending Request to API Endpoints<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Sending_POST_Request\" >Sending POST Request<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Sending_GET_Request\" >Sending GET Request<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Sending_PUT_Request\" >Sending PUT Request<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Sending_DELETE_Request\" >Sending DELETE Request<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_a_CRUD_API\"><\/span>What is a CRUD API?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>CRUD is the abbreviation for Create, Read, Update and Delete. These are the four primary operations performed in databases.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Create(C)<\/strong>: The operation adds new entries in the database table or collection.<\/li><li><strong>Read(R)<\/strong>:  The operation reads the data from the database and returns it based on search parameters.<\/li><li><strong>Update(U)<\/strong>: The operation modifies the existing entry in the database.<\/li><li><strong>Delete(D)<\/strong>: The operation removes an entry from the database table or collection. <\/li><\/ul>\n\n\n\n<p>Therefore, CRUD API refers to the API that performs these various operations. It can create, read, update and delete records in the database using the following HTTP methods.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>GET<\/strong>: It reads the data from the server.<\/li><li><strong>POST<\/strong>: It creates new resources in the server.<\/li><li><strong>PUT<\/strong>: It updates the data in the server. It takes parameters to identify the specific data item. It updates the whole content of the specific document.<\/li><li><strong>DELETE<\/strong>: It deletes the data in the server. It also takes the parameter in the request to identify the item as in the PUT method.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Build_a_CRUD_API_with_Nodejs_and_MongoDB\"><\/span>How to Build a CRUD API with Node.js and MongoDB<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The article will walk you through the steps of creating a CRUD API using the Node.js Express framework. At the end of the article, you will create a Task Management App that lets you create, view, modify and remove the tasks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_the_Project\"><\/span>Create the Project<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>If you don&#8217;t have Node installed on your computer, you can download it from the <a href=\"https:\/\/nodejs.org\/en\/download\/\" data-type=\"URL\" data-id=\"https:\/\/nodejs.org\/en\/download\/\" target=\"_blank\" rel=\"noopener\">Node.js website<\/a>. The <code>npm<\/code> package manager comes with the installation of Node.js, which will be used to install the packages and dependencies while creating the CRUD API. You can view the <code>npm<\/code> version installed in your system with the following command.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>$ npm -v\n8.6.0<\/code><\/pre>\n\n\n\n<p>Now, you are ready to go. Let&#8217;s start the project by creating a directory <em>task-management-app<\/em>. Don&#8217;t hesitate to name your directory as your wish. <\/p>\n\n\n\n<p>The first step in the project is to create the soul of your project, the <code>package.json<\/code> file. Ensure you are inside the project directory and type the following command in the terminal.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>npm init -y<\/code><\/pre>\n\n\n\n<p>The above command creates a file named <code>package.json<\/code> that is responsible for running the scripts and installing the dependencies in your project. The <code>y<\/code> flag used in the command indicates to use the default values instead of asking the questions. The initial <code>package.json<\/code> file looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>\/\/package.json\n{\n  \"name\": \"task-management-app\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\"\n  },\n  \"keywords\": &#91;],\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Install_the_Packages_and_Tools\"><\/span>Install the Packages and Tools<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The next step is to install the dependencies to your project. As stated earlier, you will be using <code>npm<\/code> to install the dependencies. Use the following command to install the dependencies to your project.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>npm i express mongoose dotenv\nnpm i -D nodemon<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><a href=\"https:\/\/www.npmjs.com\/package\/express\" target=\"_blank\" rel=\"noopener\">express<\/a><\/strong>: It is a Node.js framework for creating a web application&#8217;s server and back-end architecture.<\/li><li><strong><a href=\"https:\/\/www.npmjs.com\/package\/mongose\" target=\"_blank\" rel=\"noopener\">mongoose<\/a><\/strong>: It is a Node.js library for modeling the Object Data for MongoDB. In simpler terms, mongoose enables the application to communicate with the MongoDB database.<\/li><li><strong><a href=\"https:\/\/www.npmjs.com\/package\/dotenv\" data-type=\"URL\" data-id=\"https:\/\/www.npmjs.com\/package\/dotenv\" target=\"_blank\" rel=\"noopener\">dotenv<\/a><\/strong>: It is a package that loads the environment variables to the application from the <code>.env<\/code> file. <\/li><li><strong><a href=\"https:\/\/www.npmjs.com\/package\/nodemon\" target=\"_blank\" rel=\"noopener\">nodemon<\/a><\/strong>: It is a tool that enables the express server to restart automatically after changes have been detected in the code. Notice, the use of the <code>-D<\/code> flag while installing it. The flag indicates that <code>nodemon<\/code> is a development dependency, meaning it only works in the development environment.<\/li><\/ul>\n\n\n\n<p>After the installation of the dependencies, the <code>package.json<\/code> file looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>\/\/package.json\n{\n  \"name\": \"task-management-app\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\"\n  },\n  \"keywords\": &#91;],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"dotenv\": \"^16.0.1\",\n    \"express\": \"^4.18.1\",\n    \"mongoose\": \"^6.4.4\"\n  },\n  \"devDependencies\": {\n    \"nodemon\": \"^2.0.19\"\n  }\n}\n<\/code><\/pre>\n\n\n\n<p>To test the API endpoints, you need to install one more tool in your system, <a href=\"https:\/\/learning.postman.com\/docs\/getting-started\/installation-and-updates\/\" target=\"_blank\" rel=\"noopener\">Postman<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_the_Express_Web_Server\"><\/span>Creating the Express Web Server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Create a file <code>server.js<\/code> in the root project directory. In <code>server.js<\/code>, require the <code>express<\/code> library, which is the backbone of your application. <\/p>\n\n\n\n<p>Next, require the <code>dotenv<\/code> library and invoke the <code>config()<\/code> method. Consequently, it enables you to read the environment variables stored in the <code>.env<\/code> file with the <code>process.env<\/code> global variable. Then, create your Express application in an  <code>app<\/code> variable as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\nconst express = require('express')\nconst dotenv = require('dotenv').config()\nconst app = express()<\/code><\/pre>\n\n\n\n<p>Create a file <code>.env<\/code> in the project directory and write the following.<\/p>\n\n\n\n<pre class=\"wp-block-code language-env\"><code>\/\/.env\nPORT=8000<\/code><\/pre>\n\n\n\n<p>Now, you can access the <code>PORT<\/code> environment variable and listen on that port as follows in <code>server.js<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\nconst port = process.env.PORT\napp.listen(port, () =&gt; console.log(`app running on port ${port}))\n<\/code><\/pre>\n\n\n\n<p>Here, the <code>listen()<\/code> method creates a web server, and your application is live on the local server. However, you need to add a little tweak to run your server with the <code>nodemon<\/code> tool. For that, add the following line in the scripts key in the <code>package.json<\/code> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>\/\/package.json\n \"scripts\": {\n    \"server\": \"nodemon server.js\"\n  },<\/code><\/pre>\n\n\n\n<p>The wait is over. You can run your application with the command <code>npm run server<\/code>. Now  you don&#8217;t need to restart your server every time you make changes in your code as<code>nodemon<\/code> will take care of it for you.<\/p>\n\n\n\n<p>As you will be working with JSON and urlencoded data while using Postman, you need some tool to parse these kinds of requests. The good news is Express has built-in middlewares for these purposes and just needs to include these lines in the <code>server.js<\/code> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\napp.use(express.json())\napp.use(express.urlencoded({extend:false}))<\/code><\/pre>\n\n\n\n<p>The final <code>server.js<\/code> file looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\nconst express = require('express')\nconst dotenv = require('dotenv').config()\nconst port = process.env.PORT\n\nconst app = express()\napp.use(express.json())\napp.use(express.urlencoded({extend:false}))\n\napp.listen(port, ()=&gt;console.log(`app running on port ${port}<code>))<\/code><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Routes\"><\/span>Creating Routes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now that the Express server is up and running, it&#8217;s time to create the routes in your application.&nbsp;<strong>Routing allows you to handle the HTTP requests by assigning the requests to the specific handler called controllers<\/strong>. Since you are creating a CRUD application, the routes will handle the four HTTP methods stated earlier in the article.<\/p>\n\n\n\n<p>First, create a file named <code>taskRoutes.js<\/code> and add the following line of codes to the file. <\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskRoutes.js\nconst express = require(\"express\");\nconst router = express.Router();\n\nconst {getTasks, setTask, updateTask, deleteTask} = require('.\/taskControllers.js')\n\nrouter.get('\/', getTasks)\nrouter.post('\/', setTask)\nrouter.put('\/:id', updateTask)\nrouter.delete('\/:id', deleteTask) \n\nmodule.exports = router<\/code><\/pre>\n\n\n\n<p>The router object handles the different requests to your application. When the server receives a GET request the Express <code>get()<\/code> method passes the control to the <code>getTasks<\/code> controller. Likewise, the controllers <code>setTask,<\/code> <code>updateTask<\/code>, and <code>deleteTask<\/code> will handle the POST, PUT and DELETE requests, respectively.<\/p>\n\n\n\n<p>While updating and deleting a data item, you need to specify the item in the route with some identification. Therefore, the<code> \/:id<\/code> parameter is used in the <code>put()<\/code> and <code>delete()<\/code> methods. <\/p>\n\n\n\n<p>Now that the creation of routes has been completed, it is necessary to export the <code>router<\/code> object. Also, add the following line to require the router in <code>server.js<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\napp.use('\/tasks', require('.\/taskRoutes'))<\/code><\/pre>\n\n\n\n<p>The <code>\/tasks<\/code> route is appended to the port (<code>const port = process.env.PORT<\/code>) of the web server. For instance, the URL of the GET route will be <code>http:\/\/localhost:8000\/tasks\/<\/code>.<\/p>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Note:<\/strong>&nbsp;As of now, the routes won&#8217;t work as the controllers used in the <code>taskRoutes.js<\/code> have not yet been created. For now, require them from a file <code>tasksController.js<\/code> which we will create later on.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Connecting_the_Application_to_the_Database\"><\/span>Connecting the Application to the Database<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>You need a database to store, retrieve and manage the data for your application. You will be using MongoDB for this purpose. You can still download MongoDB locally in your system. Since the article is based on MongoDB Atlas, I recommend using Atlas.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Cluster\"><\/span>Creating a Cluster<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Sign in to <a href=\"https:\/\/www.mongodb.com\/atlas\/database\" target=\"_blank\" rel=\"noopener\">MongoDB Atlas<\/a>, a cloud database service you will use for your application. Or, if you have not created an account yet, create the account. <\/p>\n\n\n\n<p>Next, choose the shared&nbsp;<strong>Shared<\/strong>&nbsp;plan, which is free. Then, fill in the relevant information in the picture below and create the cluster.<\/p>\n\n\n<div class=\"wp-block-image is-style-default\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"701\" height=\"924\" src=\"http:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/mongo-aws.png\" alt=\"\" class=\"wp-image-3173\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/mongo-aws.png 701w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/mongo-aws-228x300.png 228w\" sizes=\"auto, (max-width: 701px) 100vw, 701px\" \/><figcaption>Options for creating a cluster in MongoDB<\/figcaption><\/figure>\n<\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Database_Account\"><\/span>Creating Database Account<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Create a database user account with a username and password.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"669\" height=\"436\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/credentials-mongo.png\" alt=\"\" class=\"wp-image-3176\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/credentials-mongo.png 669w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/credentials-mongo-300x196.png 300w\" sizes=\"auto, (max-width: 669px) 100vw, 669px\" \/><figcaption>Form for creating a MongoDB database user account<\/figcaption><\/figure>\n<\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Adding_IP_Address_to_Access_List\"><\/span>Adding IP Address to Access List<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>After that, choose&nbsp;<strong>My Local Environment<\/strong>&nbsp;and add your IP address to the Access List. Then, click the button&nbsp;<strong>Finish and Close<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"634\" height=\"566\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/mongo-ip.png\" alt=\"\" class=\"wp-image-3175\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/mongo-ip.png 634w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/mongo-ip-300x268.png 300w\" sizes=\"auto, (max-width: 634px) 100vw, 634px\" \/><figcaption>Form for adding IP Address to Access List<\/figcaption><\/figure>\n<\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Collection\"><\/span>Creating a Collection<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>A collection in a NoSQL database like MongoDB is equivalent to the table in a relational database like SQL.<\/strong>&nbsp;After creating the cluster, navigate to the&nbsp;<strong>Collections<\/strong>&nbsp;tab and click&nbsp;<strong>Add My Own Data<\/strong>&nbsp;to create your collection. Fill in the information about your collection as follows.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"320\" height=\"333\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/collection-mongo.png\" alt=\"\" class=\"wp-image-3177\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/collection-mongo.png 320w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/collection-mongo-288x300.png 288w\" sizes=\"auto, (max-width: 320px) 100vw, 320px\" \/><figcaption>Form for creating database and collection name<\/figcaption><\/figure>\n<\/div>\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Connecting_the_Application_to_the_Database-2\"><\/span>Connecting the Application to the Database<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Navigate to the&nbsp;<strong>Overview<\/strong>&nbsp;tab and click on&nbsp;<strong>Connect<\/strong>. Next, click on the second option,&nbsp;<strong>Connect your application<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"492\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/connect-mongo.png\" alt=\"\" class=\"wp-image-3179\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect-mongo.png 640w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect-mongo-300x231.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect-mongo-260x200.png 260w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect-mongo-87x67.png 87w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><figcaption>Options to choose a database connection method<\/figcaption><\/figure>\n<\/div>\n\n\n<p>Then, select the driver and its version as in the picture below. A connection string will appear. After copying the connection string, click the <strong>Close<\/strong> button.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"516\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/connect.png\" alt=\"\" class=\"wp-image-3180\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect.png 640w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/connect-300x242.png 300w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><figcaption>Connecting the database to the application<\/figcaption><\/figure>\n<\/div>\n\n\n<p>Open the <code>.env<\/code> file in your project and paste the connection string, which is similar to the following<\/p>\n\n\n\n<pre class=\"wp-block-code language-env\"><code>\/\/.env\nMONGO_URI=mongodb+srv:\/\/subodh:subodh789@mycluster.kdbit.mongodb.net\/taskManagementApp?retryWrites=true&amp;w=majority\n<\/code><\/pre>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Note:<\/strong>&nbsp;Do not forget to replace <code>&lt;password&gt;<\/code> with your database password, and make sure to add the database name in the URI. Here, the name of the database is <code>taskManagementApp<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Setting_the_Database_Connection\"><\/span>Setting the Database Connection<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>In the project directory, create a file <code>db.js<\/code> and use the <code>connect()<\/code> method of the <code>mongoose<\/code> library to establish a database connection to the application.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/db.js\nconst mongoose = require('mongoose')\n\nconst connectDB = async ()=&gt;{\n    try{\n        const con = await mongoose.connect(process.env.MONGO_URI)\n\n        console.log(`Database Connection successfully established: ${con.connection.host}`)\n    } catch(error){\n      console.log(error)  \n    }\n}\n\nmodule.exports = connectDB<\/code><\/pre>\n\n\n\n<p>The <code>connect()<\/code> method takes the connection string as the parameter which is stored in the <code>.env<\/code> file in the <code>MONGO_URI<\/code> variable. The code snippet above shows the variable is accessed with the <code>process.env<\/code> global variable.<\/p>\n\n\n\n<p>After importing the <code>connectDB<\/code> function, require it in the <code>server.js<\/code> file and invoke the function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/server.js\nconst express = require('express')\nconst dotenv = require('dotenv').config()\nconst port = process.env.PORT\n\nconst connectDB = require('.\/db')\n\nconnectDB()\n\nconst app = express()\n\napp.use(express.json())\napp.use(express.urlencoded({extend:false}))\n\napp.use('\/tasks', require('.\/taskRoutes'))\n\napp.listen(port, ()=&gt;console.log(`app running on port ${port}`))<\/code><\/pre>\n\n\n\n<p>Next, restart the server as the <code>.env<\/code> file has been changed. The output in the terminal looks like this.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>&gt; task-management-app@1.0.0 server\n&gt; nodemon server.js\n\n&#91;nodemon] 2.0.19\n&#91;nodemon] to restart at any time, enter `rs`\n&#91;nodemon] watching path(s): *.*\n&#91;nodemon] watching extensions: js,mjs,json\n&#91;nodemon] starting `node server.js`\napp running on port 8000\nDatabase Connection successfully established: mycluster-shard-00-01.kdbit.mongodb.net<\/code><\/pre>\n\n\n\n<p>It shows that the application is connected with the MongoDB database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Model\"><\/span>Creating Model<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong>The model is the interface between the MongoDB database and the application&#8217;s business logic.<\/strong>&nbsp;You can define the data you want to store by creating a model. Additionally, the model is responsible for establishing the relationship between different objects in your application. For now, you will create a model for tasks.<\/p>\n\n\n\n<p> Create a file <code>taskModel.js<\/code> in the root directory of the project. Inside the file, create a schema<code>taskSchema<\/code> as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskModel.js\nconst mongoose = require('mongoose');\n\nconst taskSchema = mongoose.Schema(\n    { \n        task:{\n            type:String,\n            required:&#91;true, 'Please add a task'],\n        }\n    }, {\n        timestamps: true\n    }\n)\n\nmodule.exports = mongoose.model('Task', taskSchema)<\/code><\/pre>\n\n\n\n<p>Here, <code>taskSchema<\/code> defines the construct and content of your document. There are two contents in the schema, which are <code>task<\/code> and <code>timestamps.<\/code> At the end of the file, the schema is imported as <code>Task<\/code> using the mongoose <code>model<\/code> property.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Controllers\"><\/span>Creating Controllers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong>The controller acts as an interface between the data and the presentation layers.<\/strong>&nbsp;In other words, the controller receives the data from the model, performs operations, and passes it to the presentation model.&nbsp;<strong>It queries data from the model and sends the data as a response in the JSON format.<\/strong><\/p>\n\n\n\n<p>Earlier, you required a controller <code>taskControllers.js<\/code> while creating <code>taskRoutes.js<\/code> and used four controllers in the routes:<code>getTasks<\/code>, <code>setTask<\/code>, <code>updateTask<\/code> and <code>deleteTask<\/code>. Now, you will create the exact file and create the function controllers. <\/p>\n\n\n\n<p>First, create the file <code>taskControllers.js<\/code> in the root directory. <\/p>\n\n\n\n<p>Then, you need to require the <code>taskModel<\/code> to fetch the data from the database.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskController.js\n\nconst Task = require('.\/taskModel')<\/code><\/pre>\n\n\n\n<p>Now it&#8217;s time to create the controllers for the CRUD operations.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"CREATE\"><\/span>CREATE <span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>The mongoose <code>create()<\/code> function allows you to add new items to the database.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskControllers.js\nconst setTask = (req, res)=&gt;{\n    Task.create({\n        task: req.body.task,\n    }).then(task=&gt;{\n        res.status(200).json(task)\n    })\n    .catch(err=&gt;{\n        res.json(err)\n    })\n}<\/code><\/pre>\n\n\n\n<p>In the above code snippet, <code>req.body.task<\/code> will request the form data from the user. You can supply the data as<code>application\/x-www-form-urlencoded<\/code> content type from Postman.<\/p>\n\n\n\n<p>After creating a new data item, the document is returned as a response. If the creation fails, an error is returned.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"READ\"><\/span>READ<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>The mongoose <code>find()<\/code> function returns specific data from the database according to the query.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskControllers.js\nconst getTasks = (req, res)=&gt;{\n    Task.find()\n    .then(tasks=&gt;{\n        res.json(tasks)\n    })\n    .catch(err=&gt;{\n        res.json(err)\n    })\n}<\/code><\/pre>\n\n\n\n<p>Since the <code>find()<\/code> function has no arguments in the code above, it returns all the data items from the database. In case of failure, an error is returned.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"UPDATE\"><\/span>UPDATE<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>The <code>findByIdAndUpdate()<\/code> method searches the particular data item and replaces it with the new value.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/tasksController.js\nconst updateTask = (req, res)=&gt;{\n    Task.findByIdAndUpdate(req.params.id, req.body, {\n        new:true,\n    })\n    .then(updatedTask=&gt;{\n        res.json(updatedTask)\n    })\n    .catch(err=&gt;{\n        res.json(err)\n    })\n}<\/code><\/pre>\n\n\n\n<p>The above code finds the task with the <code>id<\/code> supplied as a parameter in the request. Then, the new task obtained from <code>req.body<\/code> replaces the old task. If everything goes right, it returns the updated task. Otherwise,  an error will be sent as a response.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"DELETE\"><\/span>DELETE<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>The <code>findByIdAndDelete()<\/code> function finds the record through its <code>id<\/code> and deletes it from the database.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/tasksController.js\nconst deleteTask = (req, res)=&gt;{\n    Task.findByIdAndDelete(req.params.id)\n    .then(task=&gt;{\n        res.json(task)\n    })\n    .catch(err=&gt;{\n        res.json(err)\n    })\n}<\/code><\/pre>\n\n\n\n<p>Here, the task with the specific id is deleted, and the document is returned as a response. An error is returned as a response if it fails to delete the document.<\/p>\n\n\n\n<p>After creating the controllers, do not forget to export the controllers at the end of the <code>tasksController.js<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/taskController.js\nmodule.exports = { setTask, getTasks, updateTask, deleteTask}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Sending_Request_to_API_Endpoints\"><\/span>Sending Request to API Endpoints<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now that the CRUD API has been created, it is time to test the API by sending HTTP requests to the endpoints. You will be using Postman for testing the API. The table below shows the API endpoints.<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table class=\"has-fixed-layout\"><thead><tr><th>Methods<\/th><th>URLs<\/th><th>Descriptions<\/th><\/tr><\/thead><tbody><tr><td>GET<\/td><td>\/tasks\/<\/td><td>Display all the tasks<\/td><\/tr><tr><td>POST<\/td><td>\/tasks\/<\/td><td>Create a new task<\/td><\/tr><tr><td>PUT<\/td><td>\/tasks\/id<\/td><td>Update the existing task<\/td><\/tr><tr><td>DELETE<\/td><td>\/tasks\/id<\/td><td>Delete the existing task<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Sending_POST_Request\"><\/span>Sending POST Request<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>In Postman, open a new tab, enter <code>http:\/\/localhost:8000\/tasks\/<\/code> in the URL bar and select POST from the drop-down menu. Next, click on the Body option right below the URL bar. Then, chose the <code>x-www-form-urlencoded<\/code> and write <code>task<\/code> for the key and <code>my first task<\/code> for value options. After that, click on the <strong>Send<\/strong> button.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1489\" height=\"582\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/post-edited.png\" alt=\"\" class=\"wp-image-3219\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post-edited.png 1489w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post-edited-300x117.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post-edited-1024x400.png 1024w\" sizes=\"auto, (max-width: 1489px) 100vw, 1489px\" \/><figcaption>The first POST request<\/figcaption><\/figure>\n<\/div>\n\n\n<p>You just sent a POST request to the server with some payload. After the request is received, a new document is created in the database and sent as a response. Again, send another POST request as follows:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"406\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/post2-1024x406.png\" alt=\"\" class=\"wp-image-3182\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post2-1024x406.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post2-300x119.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/post2.png 1476w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>The second POST request<\/figcaption><\/figure>\n<\/div>\n\n\n<p>Notice that <code>task<\/code> has the value <code>my third task<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Sending_GET_Request\"><\/span>Sending GET Request<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>You have created two documents and can send the GET request to the server to read those documents from the database. Write the URL <code>http:\/\/localhost:8000\/tasks\/<\/code> and send the GET request.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"502\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/get-1024x502.png\" alt=\"\" class=\"wp-image-3183\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/get-1024x502.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/get-300x147.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/get.png 1508w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Sending GET request<\/figcaption><\/figure>\n<\/div>\n\n\n<p>In response, both documents are returned from the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Sending_PUT_Request\"><\/span>Sending PUT Request<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Remember, you created a task that says <code>my third task<\/code>. Suppose that it was a mistake. With a PUT request, you can change  it to <code>my second task<\/code>. For that, grab the id of  <code>my third task<\/code> and write the URL as <code>http:\/\/localhost:8000\/tasks\/&lt;id&gt;<\/code> where <code>&lt;id&gt;<\/code> is the id of the task. In my case, the url is: <code>http:\/\/localhost:8000\/tasks\/62d4355f2cd70e918280d498<\/code>.<\/p>\n\n\n\n<p>Choose PUT from the drop-down menu. Next, write the value to be updated, as shown in the picture below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"406\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/put-1024x406.png\" alt=\"\" class=\"wp-image-3185\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/put-1024x406.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/put-300x119.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/put.png 1483w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Sending PUT request<\/figcaption><\/figure>\n<\/div>\n\n\n<p>The document is updated in the database, and the response returns the updated document.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Sending_DELETE_Request\"><\/span>Sending DELETE Request<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The URL structure of the DELETE request is similar to the PUT request. It should have the id of the document which is to be deleted.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"393\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/07\/delete-1024x393.png\" alt=\"\" class=\"wp-image-3186\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/delete-1024x393.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/delete-300x115.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/delete.png 1487w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Sending DELETE request<\/figcaption><\/figure>\n<\/div>\n\n\n<p>As a response, the deleted document is returned. However, the data is deleted from the database.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Congratulations! You created a task management CRUD API on top of the Express framework using Node.js and MongoDB. This article demonstrated how to set up an Express server, manage the routes, create the models and controllers, and use a persistent database MongoDB to build a CRUD API. By this point, I hope you are able to create a CRUD API from scratch and implement it in your projects.&nbsp;<\/p>\n\n\n\n<p><strong>Was this article helpful in that regard?<\/strong><\/p>\n\n\n\n<p>Let us know your thoughts with a reply on our <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">APIs are the interface that makes communication between the software components like the server, database, and client possible.<br><br>Want to develop your own API? <br><br>We got you!<br><br>We create a guide to building a CRUD API with <a href=\"https:\/\/twitter.com\/hashtag\/Nodejs?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#Nodejs<\/a> and <a href=\"https:\/\/twitter.com\/hashtag\/MongoDB?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#MongoDB<\/a> <a href=\"https:\/\/t.co\/rnFSM1vqCh\">https:\/\/t.co\/rnFSM1vqCh<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1549899939953655808?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">July 20, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Have you ever wondered how the front end and the back end work together to form a complete full-stack application? You probably have heard the term API(Application Programming Interface).&nbsp;It is a mechanism with a functional role that facilitates the communication between the front end and the back end in a web application.&nbsp;API is the interface &#8230; <a title=\"Complete Guide to Build a CRUD API with Node.js and MongoDB\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/complete-guide-to-build-a-crud-api-with-node-js-and-mongodb\/\" aria-label=\"More on Complete Guide to Build a CRUD API with Node.js and MongoDB\">Read more<\/a><\/p>\n","protected":false},"author":7,"featured_media":3213,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[23,16,14],"tags":[],"class_list":["post-2936","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js","category-javascript","category-tutorial","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2936","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2936"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2936\/revisions"}],"predecessor-version":[{"id":3227,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2936\/revisions\/3227"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3213"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2936"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2936"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2936"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}