ExpressJS & MongoDB — API using external Routes and Controllers

Cris Ferreira Pires
3 min readMar 24, 2021

from: sambarros.com

We will be using ARC to test our API methods.

First we need to create a MongoDB locally to do so is simple we only need to go it’s official website and download the client. (here)

There are plenty of tutorials out there on MongoDB so assuming you know how to install it and set it up we are moving forward.

In this project we will be separating everything into it’s own file. This improves the readability of the code and makes it easier to develop.

The folder structure should be looking like this.

Folder Structure in VSCode
Main.js File

Here we can see we are using some external dependencies to make this api work the way we want it to.

Dependencies:

  • expressjs
  • body-parser
  • mongoose
Routes.js file

Express needs to be imported here again so that we have access to the Router() function.

This function makes it so that we don’t need to pass “app” into the routes module.

Controller.js File

In this file we have the code to control the data base. We have here the crud methods.

  • Create
  • Read
  • Update
  • Delete
Model.js File

On this one we set a schema for the database, this is how it should look like, and what types of items are accepted into it.

Now to the tests, we will be using ARC to send requests to the API, and on some of this requests we need to set a body. For that we also need to select the type of data. In our case we want it to be “application/json”.

Adding a user:

Post Method

After adding the user, the server responds with the user data as it is in the database.

Listing all users:

Listing

User specific info:

Get Method

This shows info on a specific user providing it’s _id.

Patching a user:

Patch Method

The user we added know has a different value on its address.

Put method is done in the same way as patch.

Put Method

We are assuming one will be used to change user attributes, while the other, PUT, will be used to add a missing field.

Deleting a user:

Delete Method

Finally if we no longer want the user in the data base we can delete it. This method only deletes the user with the provided _id.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response