Beginner tutorial for NodeJS, express and MongoDB

Yanisa Suntonyotin
Thinc.
Published in
9 min readNov 1, 2018

Hello everyone! Today we’re going to teach you about how to write “Backend” by using Nodejs, express, and MongoDB. For some people who may not know what “Backend” or “Express” is? Why is it important? You guys can follow the link below!

After you finished reading it, I guess can see someone’s pale face sitting in front of the screen and think

“Oh…Why am I doing what I’m doing right now?”

…BUT!!!

Please don’t shut this Medium tab immediately because in this tutorial we’ll teach you the basic usage of it without considering things like “Best Practice” or those confusing concept(yet🤪) We’ll mainly focus on how to make you understand the most and still be able to use it in the real world.

ps. For those who may interested in how to write a code in a standard way or want to know more about deep down concept, please stick with the next tutorial.

Before we start coding, let’s see what we have to use first. In this tutorial we’ll use only 4 main tools.

  1. NodeJS for run server
  2. MongoDB as database to collect the data
  3. Your favour editor. If you don’t have one, we suggest using VSCode 😊
  4. Postman for testing request and backend which we are going to write.

Part 1: Getting started

To begin with, please download starter template from https://github.com/chutipon29301/medium-express-mongo-tutorial-1

After finished then open downloaded folder via editor

you’ll see something like this

Next, open terminal or cmd and enter to the template folder. After being inside the folder, you can now install all of the sufficient package by typing npm install

If you’ve already finished installing, you’ll get the folder name node_modules appear inside the folder. This node_modules folder will collect all dependency we use in this project altogether.

Note: If you’re Github user, I suggest you should gitignore this folder cause it’s too large

When we loaded all of the package we need into the project, in the next step we’ll test and check whether the project (which we spend a lot of time downloading) can be used or not. We will use npm start command and this is what we desperately want to see…

If you don’t get the result like this, don’t freak out yet. We’ll basically fix the problem, together, please follow the instruction below.

  1. If cannot find npm: Firstly, check whether you correctly install NodeJS or not because normally npm will come with NodeJS installer already.
  2. If cannot find dependency : check whether you correctly install package in the appropriate folder (Please allow me to remind you that you must call npm install in template folder not in the outer folder)

Finally, open your browser and go to http://localhost:3000/ping what we suppose to get will look like this

That’s the end of part 1. Quite a confusing right? Actually we just want to check the environment, download and run the project we’ve prepared for you in this tutorial.

Part 2: WebServer

In this part will talk about our main protagonist ….MongoDB !!! Beginner may not know what database is used for? So let me clarify first.

Database is responsible for collecting the data permanently which MongoDB is one of the database that collect data in form of object. The benefit we gain is that MongoDB is quite easy to manage and easier to understand than others.

Structure of mongoDB

When we want to use mongoDB, the first thing we need to know is

The database’s name is what we name database we want to use. Mostly we will use the same name as the project name.

Secondly, in each database there’ll be a collection. THIS collection is like a folder which will manage data inside database.

Lastly, in each collection there’ll be a document or the data of each object we want to collect.

After we see a big picture of what we are gonna use, how it looks like and what is its structure, now it’s time for coding!!! 🤩🤩🤩🤩

Above is fundamental code which we prepared for you. Let’s see what it is used for…

In this project we’ll use 2 dependency which is express and body-parser

Whileexpress will be used for create webserver that will communicate with client, body-parser will transform the data sent by client. What we can do now is to initialize bodyParser and app in order to collect 2 value that we’re gonna use.

In the next line, you’ll see that something is messing around bodyParser and app .What we do here is to tell express or app to use bodyParser to transform body value which we’ll use in this project.

This is where we tell webserver (created by express) to use port 3000 in order to run server.

Lastly, is to tell app to wait for receiving GET request by using path /ping and sent {msg: "pong"} to a person who call /ping

Next step, it’s time to use Mongo! Node already prepared mongoDB which is official driver for NodeJS for you, so what you have to do is just type npm install mongodb --save in terminal or cmd in order to install this dependency.

Then back to ourindex.js file and import mongoDB ,which we just installed, to the file.

After that we’ll start connecting to the database. We need database url (assume that we use database within the PC) which is mongodb://localhost:27017 but if you want to use online database, you only need to change the url into mongodb://<url-or-ip-address>:27017 .

As you can see from the code above, we move app.listen into MongoClient.connect() since we want server to start running after connected to the database right away.

In this code, we have 2 extra part added which is if(error) throw error; this one is for checking an error from connecting database. If there’s error detected, we’ll throw error out. Another part is var db = client.db("MediumTutorial") this one is for initializing variable to collect our database. What we insert inside db() is the name of the database.(We already mentioned that before, you can scroll up to recall your memory😁)

Next, we’ll talk about the overview of what we will do in this tutorial. What we will write today is the backend that allow user to create, list, edit, delete and login.

Part 2.1: List user

Syntax of mongo which we will use in the request isfind and toArray .

Let’s begin with

db is the variable we’ve already initialized before to collect the instance of database.collection is to call collection’s name inside database, let’s assume the name is users .find is to find data in collection.toArray will bring data we found and transform it in form of array of object.

ps.We’ll discuss more about find in the next session when we do request login.

After we finish coding, let’s test it! Are these bunch lines of code work correctly? Firstly, if you didn’t run npm start then run it first, the result should be as same as what we mentioned before in part 1.We can access to the request we wrote by using Postman and go to the link localhost:3000/listUsers and what we got is….empty array! Why is that? The answer is so easy… We didn’t create user yet. So in the next part we’ll talk about how to create user.

Note: For people who use mac, please run mongo process first before run npm start by typingmongod on terminal.

Part 2.2: Create user

Ahhhhh! Finally we reach part 2.2. In this part we’ll look at how we can create user or insert data into database. The command we use in this part is insertOne for insert data into database and what you should know is _id is a primary key of collection we want to collect.

Some may confused… What exactly is primary key? To describe in the simplest way, it is the field that each collection must not have in similar which is email that client sent to us. If we tried to insert document that have repeating _id the insertion process will not be success.

And now, it’s time for testing (again). Similarly, if you didn’t run npm start then run it first, then use postman to sent request.

In the first time created, what we should receive is OK because we already wrote in the code above that if has no error then sentOK back.

But if we tried to add user by existing email, we’ll get the same error as below. This show the property of _id we’ve mentioned before.

After we successfully add user, then go back where request is written in part 1 and check. You’ll see that you won’t get empty array back anymore but get the array that include the user we recently add back instead.

Part 2.3: Edit user

In this part, we’ll talk about how to edit data in database. As you can see above, We use updateOne to edit data in the target document(one object in line is one document) by insert the parameter that identify the field(can be one field or more) of target document we want to edit and then insert the new updated value in the following parameter. You’ll now get the updated document on your database.

// before
[
{_id:1, name: "Apple"},
{_id:2, name: "Huawei"},
]
updateOne({_id:2},{$set:{name:"Pixel"}});// after
[
{_id:1, name: "Apple"},
{_id:2, name: "Pixel"},
]

You’ll see that in updateOne will have weird syntax called$set this will allow you to edit only one field in target document and other field will remain the same.

Part 2.4: Login

Next, we’ll try to create request login. What we’ll do in this request is to find user 1 who has the similar email with user we get then check whether the password is correct or not.

We use findOne to find only 1 document and return as a result. What we can insert inside findOne is the condition of what we want to find which is an email that we collect in _id field. So we got condition object like this{_id: req.body.email} and when we try to request via postman, we’ll get return value as true or false .

Part 2.5: Delete

Finally, we’ll delete user from database which is quite easy (really easy…trust me) because we already know about findOne so we change findOne into deleteOne .That’s all we have to do in order to delete document.

When we try to delete and list user, you will get the result as shown below…

And now here we are, at the last session of this article. For those people who interested in using mongoDB in other application, you can read all of mongo function in this link.

Lastly, we’ve prepared the complete code in the folder name final. For those who cannot catch up with the tutorial, you can look it up if you like.

--

--

Yanisa Suntonyotin
Thinc.
Writer for

Information and Communication Engineering @Chulalongkorn University Internship@Huawei Technologies Thailand Interested in Data Science