Pages

Backend for CRUD app using NodeJS, ExpressJS, and MongoDB- Part 2

In the first part, we discussed the setup of different environments, including NodeJS, MongoDB in the cloud, and MongoDB in the NodeJS app


Follow the steps to create a strong backend for your CRUD application using NodeJS, ExpressJS, and MongoDB. In simple steps, you can understand how to build a backend for the CRUD app. 


Step 1: Create a model communicating with MongoDB

In the project folder, name the folder "models”. Build a file name project.js in the newly created folder. 


Now, import a Mongoose library in the newly created file project.js and create a new Mongoose Schema. The database schema stores your data in a database. 


Next, you need to specify the project schema (this database represents the datatype and whether it is necessary or not).


The project we created has the project name with the String type, project manager, project cost of type Number, and project status. You don’t need to create a project id because MongoDB will automatically create a project id for you. We give the projectSchema to our model at the end of the file before exporting it.


Step 2: Configure the controller and Express Router for GET requests.


Our next step is to create the "controllers" and "routes" folders. Then, in their respective folders, create projectController.js and projectRoutes.js. The directory of your projects ought to look like this:

After that, we will install and run two dependencies Express and CORS. 


npm install express


npm install cors



Now lets, import Express and CORS inside our index.js file. Next, we call express() to create an Express application, which we then assign to the app variable. Additionally, we must specify the port on which our backend service URL listens:


Next, we will select a port on our system which is not in use and create a homepage route. We will use the CORS policy on our application and then assign the port to our application.


We'll then return to our terminal and execute node index. Once more using js, we can see that the messages "Database is connected" and "Server Running on port..." are printed out.



We must now develop the GET route and the corresponding method in the controller. This GET route shows every piece of project information that is kept in the Mongo database.


In order to use projectController.js to communicate with the database, we must first import the Project schema that we created in the model's folder and then create a method to respond to the route.


The method project_get_all returns the complete list of projects that are stored in mongoDB. The method find() all projects using the Project Schema, then sorts them using the createdAt tag in descending order (newly created projects come first). When the result is ready, res replies with the status code 200 (OK) and the sorted result. Send back a 400 (Bad Request) status code if there was a problem retrieving the result.


In the projectRoutes.js, import express for Express Router and projectController for the method that we just created to response to GET route.


Then, by including the next line of code, we link the "/" page of the project route to its associated controller method. After that, we export the router.


We still have one more task to complete inside index.js. The project route needs to be added to the application.


Let's import the bodyParser and projectRoutes at the start of index.js:


The /projects signifies that you should add /projects to the end of the URL after the homepage at http://localhost:8080 to access that location.


When you go to http://localhost:8080/projects and run the node index.js command again in your terminal, an empty array will appear because our database is still empty:


 

We return to the MongoDB cloud and click the Collection button under the Cluster we initially created. Look for the Insert Document button under the Collection tab, and then enter some information. While entering data, you can use your keyboard's Tab key to advance to the following input box.



Now, go back to the http://localhost:8080/projects and refresh it. You’ll see the data get displayed now:



Therefore, this is basically You can send a request from the frontend to the backend at http://localhost:8080/projects to retrieve data.


Step 3: Create the rest of the Routes


  1. “GET /:id” Route:


Let's now create a route that allows you to retrieve a specific project by its ID. This route would be created with the following format: http://localhost:8080/projects/:id, where ":id" stands for the ID of the project you wish to retrieve.


Let's first add a method called project_get_byID() to projectController.js:


The input request known as "req" that is sent from the front end should have an id parameter (req.params.id). Then, using findById() mongoDB methods, we use the provided id to locate the project by its ID. At the very end of the file, don't forget to export the project_get_byID() method.


The controller method is then connected to the route after it has been created in projectRoutes.js.


Run node index.js once more.


Go to http://localhost:8080/projects/:id and enter the project id that you copied from your MongoDB cloud into the address bar. The database only retrieves the matching project.


  1.  “POST /” and “DELETE /:id” Routes:


We add project_create and project_delete methods to create and delete projects via HTTP requests.


MongoDB communication requires a new Project() schema for project_create. The new project data, req.body, is passed in. Next, we save() the new project to MongoDB.


For project_delete, we first get the project id. Next, we findByIdAndDelete the project whose id matches the criteria.


At the conclusion, don't forget to export project_create and project_delete. 


We connect the project_create method to the POST route in projectRoutes.js, and the project_delete method to the DELETE route.


Following that, we will attempt to run the node index.js file once more. Now, most of our coding part is completed, now let's test our new POST and DELETE routes. Now, we need something that can simulate the functionality of the front end in terms of sending requests.


Launch the Postman desktop application, and when prompted, click the "+ New" button to add a request. We have decided to call this request "POST PROJECT." When you are inside the POST PROJECT request tab, click on the dropdown to choose the POST option, and then type in http://localhost:8080/projects/ for the URL link.



In addition, select the Body tab within the POST PROJECT section of the tab bar, and after that, choose the raw option to include new project data in our request. Choose the JSON option because that is the format that our data is stored in. 



After that, select the blue button labeled Send. You can check that it has been added by visiting the Collections section of our MongoDB cloud website.




We create a new request with the title "DELETE PROJECT" in order to delete an existing project. We enter the project id we want to delete at http://localhost:8080/projects/:id and select DELETE as our request option and then click Send.



Moreover, we note that the project identified by the provided id has been removed from our cloud database.



Final thoughts:

In this blog, we have learned to create a backend for CRUD app using NodeJS, ExpressJS, and MongoDB and this is the second part. If you have not go through the first part of yet then read it first. 



No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...