A sweet kick-starter to BackEnd API Development using NodeJS, ExpressJS and MongoDB — Part 1

Hi friends, I am Yashvardhan Kukreja and I am a Full Stack Android Developer. I love to learn things and teach them. Around one year ago, I started Back End API development in NodeJS and I loved it and its impact in the world because behind every great application, there is a darn great Back End. I have planned to create a series for you which will give you a good kickstart to learn this amazing field in an easy manner.

So, I am writing this article (with some memes :P) for you to understand the basics of NodeJS with ExpressJS and MongoDB as good as possible.

I will try my best to explain the concepts and terms getting used here as descriptively as possible but still there might be some terms or concepts which you may not understand or relate to.

So, I highly recommend you to give a read to my article, Internet — Behind the scenes. It will take hardly 10 minutes to give it a read and understand. But I am darn sure that after reading it, you will surely understand the terminologies, concepts and many fundamentals related to internet and networking which will make the understanding of the back end way freaking easier.

In this part of the series, we will learn to do the following things:

  • Setting up a basic NodeJS server.

Let’s get started

Install MongoDB and NodeJS in your PC (Very easy! Google will help you there :) )

Create the project folder. Here, I am creating project folder with the name “first_proj”

mkdir first_proj

Now, go inside that folder

cd first_proj

Now, initialise the basic node files by running the command

npm init

This command will create multiple folders and files in the main directory. But the package.json is the most important one. It contains all the details of the project you are working, like the name, author, dependencies getting used, etc. We will have a look at it just in a while.

Now, Let’s install some basic dependencies so as to start with setting up the most basic functionalities of the back end app.

npm install --save mongoose express 

Woah!!! Seems like a big command. Let’s break it down.

  • npm — it calls the node package manager
Successful installation of mongoose and express will look like this

Now, after this command is successfully executed, a folder named node_modules will be created. This folder will contain all the downloaded and installed dependencies. Don’t worry, you don’t need care about it all while coding.

So now, let’s have a look at the “package.json” file.

Let me explain each and every term here:

  • name — name of your project

Ready, Set, Let’s CODE…

From here on, we will begin the coding part of our BackEnd app.

So, first of all, create a file named “index.js”.

This file is going to be the main file which after execution will connect to the database and start the server and make it functional and useful.

So, first of all, let’s declare some dependencies.

const express = require('express');
const mongoose = require('mongoose');
const app = express();

For using the functionalities of the dependencies, we declare them first and then store them in a variable. Using those variables, we access the respective functionalities.

Here, the variable app corresponds to express() object which will be used to execute the functionalities of express dependency. It is going to be used for creating every route (functionality) in the backend and making it efficiently functional.

So, now, let’s declare the port number on which our server will run.

Analogy for ease :)

Let me explain the concept of port number with a decent analogy.

Consider, you want to contact a faculty named “Ramesh” in a college. So, what you’re going to do is that you’re going to call the college on their contact number. Then, on the call, you’ll tell the receptionist that you want to talk to Ramesh sir. So, the receptionist will forward your call to the intercom number of Ramesh sir. And then, you will be able to talk to him.

In this analogy => college’s contact number === IP address

=> intercom number of Ramesh sir === Port number

In computers, a similar kind of thing happen, Server has an IP address and under that IP address, a lot of ports are there. These backend applications run on one of these ports. So, we run our applications on one of these ports.

const port = process.env.PORT || 8000;
// You can keep a different port number like, 8080 or 3000 or 8008 etc..

Here, the server will run on a port which is declared in the environment variables of server. And if it is not declared, then it will run on port number 8000.

Don’t worry regarding the environment variables thing for now. I’ll explain it later in the series where I will explain server deployment on cloud.

For now, assume the port number to be 8000. This means that whenever you run this backend application, it will run on port number 8000.

Database… Coz anything without data is boring

Now, let’s declare the database to which our server will connect and save users and stuff.

const db_link = "mongodb://localhost:27017/first_db";

Don’t freak out seeing this link XD. It’s very basic. It basically leads to a database named “first_db” on your computer.

Here, localhost means that the database we’re creating is on our computer only. And 27017 is the default port number on which mongoDB run on a machine.

Don’t worry about this, “mongodb://localhost:27017/” remains same always. Only the name of database varies in different projects.

For example, if I want to create and use a database in my computer named “aloha”, then I’ll declare, db_link = “mongodb://localhost:27017/aloha”

Now, let’s connect to this database using mongoose

mongoose.connect(db_link, function (err) {     if (err)
console.error("Error occurred while connecting to DB!");
console.log("Database connection established successfully");

Okay, I’ll explain this line by line.

“mongoose.connect” makes our backend application connect to the database corresponding to the variable “db_link”. Now, this function also returns with a callback function whose first argument is “err” which corresponds to the error which might come up on connecting to database.

So, what this means is, that if there comes an error connecting to database due to any reason, then this argument “err” will contain the details of that error.

But if database connects successfully without any error, then this argument “err” will have a null value which basically means no error.

So, in the next lines, I have defined these conditions of error/no error only.

  • console.log() is used for printing in the console.

Usually, errors are logged using console.error() .

Routing — The heart of BackEnd…. or may be the brain, Idk :P

Let’s create a GET route for homepage of our backend application :)

app.get('/homepage', function(req, res) {       res.send("Hello, World! Welcome to kickstarter for backend API development ");});

Cool, let’s get into the explanation of this snippet.

First of all, I will explain the terms used here:

  • get — Means that this function will get executed using GET request type. We can execute GET using the itself easily. Whenever, you enter anything in the search bar of the browser and press Enter, a GET request gets executed

Analogy for ease :)

Okay, so here, I think I should use a simple analogy to explain the functioning of these terms.

So, generally while programming, we create function this way

  • We declare the name of function

So, here, the input/arguments are request type, request body most of which is fetched using the variable req. The main logic is entered accordingly.

And the output returned is through the res.

So, in a nutshell, this snippet will do the following

—On running the url “http://localhost:8000/homepage” will show you “Hello, World! Welcome to kickstarter for backend API development” in the browser.

I understand that many things might be going over your head right now, but again I’d highly recommend you to give to my article Internet Behind the Scenes to deeply understand what’s happening here and what does each of the terms here mean exactly.

Running the server — Making our code come to life

app.listen(port, function() {      console.log(`App running successfully on port number ${port}...`);});

This snippet will run our server on the port number which we declared before.

Now, for running our code, you have to make somethings sure:

  • Install MongoDB and NodeJS in your PC.

Let me show you the screenshot of the final code and its output

Here, you might notice something different. The way I have coded callback functions. I have followed ECMA Script 6 for coding the functions.

So, both of the below snippets are same

function(argument) {     console.log("Aloha World");}

ECMA Script 6 manner

(argument) => {console.log("Aloha World");}

ECMA Script provide a lot convenience while coding functions, so, I’ll prefer you to give a look at it. It’s super easy to understand.


On running the command
This is the final output in your browser when enter “localhost:8000/homepage” (the route you created) in the search bar.

Final Note

Congratulations on creating and running a NodeJS server with Database connectivity !!!

In the next part, we will learn to how to create a basic application in which we will create DB models using mongoose and writing POST route for signing up users just like the way, we sign up for an account in real life.

I’ll be writing and posting further parts of this series as well. Stay tuned for them!

Thanks a lot for reading my article. If you liked my article, do give a clap :D

I hope this article was well descriptive still whenever you face any doubt or problem related to this article (or even life XD), I’d love to resolve it. Just drop me a mail :D

E-mail — yash.kukreja.98@gmail.com

Github — https://github.com/yashvardhan-kukreja

LinkedIn — https://www.linkedin.com/in/yashvardhan-kukreja-607b24142/

Site Reliability Engineer @ Red Hat | ex-Grofers | Contributing to {Cloud, Kubernetes}-native OSS