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

Solution


In the first part, we discussed the setup of different environments, including NodeJS, MongoDB in the cloud, and MongoDB in the NodeJS app. If you have not gone through the >first part yet then read it first. 


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

Make a "models" folder inside the project folder. Create a project.js file in the newly established folder. 


Create a new Mongoose Schema and import a Mongoose library into the recently created project.js file. Your data is kept in a database by the database schema. 

The project schema must then be specified (this database indicates the datatype and whether it is required or not).



Our created project has a String type project name, a project manager, a Number type project cost, and a status. MongoDB will generate a project ID for you automatically, so you don't need to do it. Before exporting the file, we give our model the projectSchema at the end.


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

Making the "controllers" and "routes" folders is the next task. Next, make projectController.js and projectRoutes.js in the appropriate folders. Your projects directory should resemble this:



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


npm install express


npm install cors



Let's import CORS and Express into our index.js file now. The Express application is then created by calling express(), and it is subsequently assigned to the app variable. We also need to provide the port that our backend service URL listens on:


The next step will be to create a homepage route and choose an idle port on our system. After assigning the port to our application, we will use the CORS policy on it.

After that, we'll go back to our terminal and run the node index. Using js once more, we can observe that the messages "Server Running on port..." and "Database is connected" are printed.


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.

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 is a problem retrieving the result.


In the projectRoutes.js, import express for Express Router and projectController for the method that we just created to respond to the 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 signify 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 go back to the MongoDB cloud and select the Cluster that we created earlier by clicking the Collection button. Navigate to the Collection tab, find the Insert Document button, and fill in the required information. Use the Tab key on your keyboard to move to the next input box while entering data.


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.


After that, we'll try to launch the node index.js file again. Now that we have finished most of the coding, let's test the newly added POST and DELETE routes. We now require a system that can replicate the front end's request-sending functionality.


Open the Postman desktop app, then select "+ New" to add a request when prompted. This request will now be referred to as "POST PROJECT." Once you are in the POST PROJECT request tab, select POST from the dropdown menu and enter http://localhost:8080/projects/ as the URL.


Moreover, open the POST PROJECT tab bar, select the Body tab, and then select the raw option to add new project data to our request. Since our data is stored in the JSON format, select that option. 



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" 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 the CRUD app using NodeJS, ExpressJS, and MongoDB and this is the second part. 


Suggested blogs: 

>How to delete documents from a mongoDB collection without an error?

>How to overwrite the contents of MongoDB via a put request in Nodejs?

>How to update a document in MongoDB with NodeJS?

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Create a One Page App with Angular.js, Node.js and MongoDB

>How to Build a RESTful API Using Node Express and MongoDB


Adequate Infosoft

Adequate Infosoft

Submit
0 Answers