Creating a backend for CRUD application with NodeJS, ExpressJS, and MongoDB (Part 2 of 2)
If you have not read part one yet, you can find it here.
In this part 2, we will cover:
- Create Model that communicates with MongoDB.
- Setup the Controller and Express Router for GET request.
- Create the rest of the routes.
PART 2
- Create Model that communicates with MongoDB.
Inside the project folder, create a folder named “models”. Create a file project.js in that folder:
We import the mongoose library to the project.js file and create mongoose Schema. A database schema is an abstract design that represents the storage of your data in a database.
Then we continue to specify the projectSchema
(this is like a template that specifies the data type and whether it is required or not).
Our project template has project name with the type of String, project status, project manager, and project cost of type Number. We don’t need to have the project id because MongoDB will automatically generate project id for us.
At the end of the file, we assign the projectSchema to our model and then export it.
2. Setup Express Router and the Controller for GET request.
Now, we create two other folders “controllers” and “routes”. Then, create projectController.js and projectRoutes.js inside their according folders. Your project directory should look like this:
Next, there are two dependencies we need to install, Express and CORS. Run each of the following commands inside your terminal to install them:
npm install express
npm install cors
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources. You can check your dependencies installation inside the package.json file:
Inside our index.js file, let’s import CORS and Express. Then, we create an Express application by calling express()
then assign it to an app
variable. Also we need to define the port where our backend service URL listens to:
Any port that is not currently used by your computer is fine. I will choose port 8080.
Next we create a homepage route and use CORS policy on our application, then assign the port to our application.
Our entire index.js file currently looks like this:
Now, we go back to our terminal and run node index.js
again, we see that both messages “Server Running on port…” and “Database is connected” are printed out.
If we go to our favorite web browser and go to “http://localhost:8080”, we see that the message is printed out on the homepage:
Now we need to create the GET route and the corresponding controller’s method for that route. This GET route displays all the project data that is stored in the Mongo database.
First, we need to import Project
schema that we created in the models folder to projectController.js so we can use it to communicate with the database.
Then, we create a method to response to the route.
project_get_all
method returns all the list of projects that is stored inside mongoDB. The method uses Project
schema to find()
all projects then sort()
them by createdAt
tag with -1
order (descending order/newly created first). Once the result
is ready, res
sends back status code 200
(OK) and the result
that has been sorted. If there is any error while getting the result
, send back the status code of 400
(Bad Request) instead.
In the projectRoutes.js, import express
for Express Router and projectController
for the method that we just created to response to GET route.
Then, we connect the “/” page of project route to its corresponding controller method by adding the following line of code. After that, we export the router.
There is one more thing we need to do inside index.js. We need to add the project route to the application.
Let’s import the projectRoutes
we just created and bodyParser
into the beginning of index.js:
Then, add this to the end of the index.js file:
The /projects
means that after the homepage of http://localhost:8080
add /projects
to go to that route (http://localhost:8080/projects).
Now re-run node index.js
command in your terminal and go to http://localhost:8080/projects, you will see an empty array displays because we don’t have any data inside our database yet:
So, we go back to the MongoDB cloud, go to the Cluster that we initially created and click on Collection
button. Inside the Collection tab, look for Insert Document
button and add some data in there. To move to the next input box while adding data, you can click on Tab
from your keyboard.
Now, go back to the http://localhost:8080/projects and refresh it. You’ll see the data get displayed now:
And basically, this is http://localhost:8080/projects is the URL which you can send a request from the frontend to get the data from the backend.
3. Create the rest of the Routes:
i) “GET /:id” Route:
Now, let’s create a route which you can get a specific project by its ID and it would look like this http://localhost:8080/projects/:id, where “:id” is the ID of the project you want to get.
Let’s create a method project_get_byID()
inside projectController.js first:
req
is the input request sent from frontend, it should has an id parameter (req.params.id
). Then we use the given id
to find the project by its ID using findById()
mongoDB methods. Don’t forget to export the project_get_byID()
method at the end of the file.
After that, inside projectRoutes.js, we create a route \:id
and connect the controller method with it.
Re-run the node index.js
command.
In you MongoDB cloud, copy an id of the project you created in the mongoDB and then go to http://localhost:8080/projects/:id where :id
is the project id that you copied. You’ll see that only the project with the matching id is retrieved from the database.
ii) “POST /” and “DELETE /:id” Routes:
Finally, we add project_create
and project_delete
methods so we can create new project or delete an existing project through an HTTP request (frontend request).
For project_create
, we create a new Project()
schema to communicate with MongoDB. We pass in it the req.body
which is the new project data. Then we save()
the newly created project to MongoDB.
For project_delete
, we first get the id
of which project needed to be deleted. Then, we findByIdAndDelete
the project with the matching id
.
And don’t forget to export project_create
and project_delete
at the end.
Inside projectRoutes.js, we connect project_create
method to the POST route, while we connect project_delete
to the DELETE route.
Then, we re-run the node index.js
. Congratulation! We are done with the coding part, now let test our new POST and DELETE routes. Now, we need something to mimic the frontend’s sending request functionality.
Open the Postman desktop app and click on + New
button to add a request. We name the request “POST PROJECT”. Inside the POST PROJECT request tab, click on the dropdown to choose POST option and type in http://localhost:8080/projects/ for the URL link.
Also inside the POST PROJECT tab, click on Body
tab and then click on raw
option to attach new project data to our request. Click on JSON option as our data is in JSON format
Then add this following data into the Body
:
Then click on the blue button Send
. Go to our MongoDB cloud website, inside the Collections, we’ll see that it has been added there.
To delete an existing project, we create a new request and name it “DELETE PROJECT”. We choose DELETE as our option for request and pass in the http://localhost:8080/projects/:id where :id
is the project id we want to delete. Then click Send
.
And we see that the project with the given id
has been deleted from our cloud database.
Congratulation! you have completed Part 2! You deserve a big round of applause and a relaxation walk.