Beginner: How to create a backend Node.js server using MongoDB

Kim Lester Tee
Sep 5, 2018 · 3 min read

We will create a mini backed Node.js server that uses a MongoDB.

First we setup our package.json file and include all the dependencies we need.

package.json

Now, we create our server.js file, the application will start from this js file. We are going to use the express framework for simplicity and CORS to handle the HTTP requests.

server.js

We now create our controller file. The controller file will be the interface from our server.js to our service file which contains the methods of putting and retrieving data from our MongoDB

data.controller.js

Going to the data.service.js, this file will contain mongoose function in putting and retrieving data from our MongoDB.

data.service.js

Now we have to create our db.js file that will connect to our application to the database.

db.js

You will notice in our db.js file that we required a ‘config.json’ file, this file will contain the connection string that leads us to our database.

config,json

Now we will create our data.model.js file, this will be the basis of our database schema for the data.

data.model.js

Lastly, we will create our error-handler.js file that will handle any error in the server application and return it.

error-handler.js

Let’s take a look of the file structure before move on.

File structure

Using NPM, we just have to run the command <npm install> in the project directory using the terminal. To run our server we have to input <npm start> and our backend server is ready to go. Below is a demonstration that our code is working. I will do another post for the front-end application in the near future.

Link for front-end tutorial https://medium.com/@kimtee92/basic-create-an-angular-4-web-app-and-use-http-client-module-f29bf4b4e22

Github link: https://github.com/kimtee92/nodebackend.git

Kim Lester Tee

Written by

Pursuing a career in programming and web development. Currently taking up Master of Information Technology at University of Technology Sydney.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade