Step by step tutorial NodeJs ExpressJs MongoDB App for Beginners (April 2017)

NODEJS EXPRESS MONGODB APPLICATION

This tutorial is written specifically for people who are planning to learn Nodejs. You may have programmed in PHP before, and willing to start your career in nodejs, then It will surely help you. I will try my best to explain you each thing in detail. We will learn about nodejs, expressjs, mongodb, mongoose, nodemon etc.

If you are new to programming then it is also fine. Grab some coffee and stay with me.

You can also download the full app.

The problem in learning NodeJS

Let’s discuss the problem first. Many of you tried to understand node. But you may have failed. The problem is not with the nodejs. Actually, you need to few things before writing your first code. That’s where most people leave it.

Another thing I see that some people are just afraid of the terminal. The reason is they actually never used one. In nodejs dealing with packages and installing them, everything is done in a terminal. So I will try to show you how you can easily manage your application.

Our Application

We are going to build a super duper simple application where people can save an article with a heading. In our application people also can view all the previous posted articles.

Things we need before starting

  1. Nodejs
  2. MongoDB
  3. A text editor

Installing NodeJs

First, go to Nodejs’s website and click on the download button. Click on the LTS version of the Node. The process is pretty simple. You just need to click next bunch of times. Nodejs will be installed in your system. The process is same for all the major operating systems.

Verify Nodejs Installation

Just open a terminal and type this code and hit enter. You will see your nodejs’s version by this.

node -v

By installing node, you will automatically get access to the node’s package manager npm. Npm comes with nodejs.

You can check your npm version with this following command. We will use  npm a lot in building nodejs apps.

npm -v

Install MongoDB

MongoDB is our server to save our data. The process is same as above. Visit  https://www.mongodb.com/download-center and choose your operating system.

Run MongoDB

After installing MongoDB, we need to start our MongoDB. So open a new terminal (for windows open a command prompt window), and type mongod

Keep this window open. We need to keep it open while we are developing our application.

Let’s get started with our Node Express App

We are done with our development setup. These things are mandatory to build a build a web application or a RESTful API with nodejs.

Now open another terminal window. Do not close the previous mongod window. You might now know, we are going to use an extremely popular nodejs web application framework, Expressjs.

Now we need to install express generator globally. To do this, run the following command

Now we can use the  express command to generate our project.

Generating our project with express

Here we will tell express to generate a project named “article-app” with the templating engine “ejs”

Now you will see a folder named article-app has been created. Now change your directory to this article app and run npm install  to install all the dependency packages we need. You might need to run  sudo npm isntall if you see permission denied message.

Are you tired?

You might feel tired now as to get started you need to do a lot of things. But that is fine. As you are just starting, it will be lot easier when you will grasp the concept behind nodejs applications.

After running npm install , you just installed all the dependencies mentioned in our package.json  file.

This package.json file holds all the necessary information about our web applications. You can read more about this here.

The Folder Structure of the ExpressJs App

Let’s discuss the folder structure. The heart of our app is the app.js file. You will see another folder named node_modules. This folder contains all the dependency code of our application. You never need to open this folder while developing.

Run the application

To run our web application type npm start in the terminal and go to http://localhost:3000/  You should see a image like this one. If not then recheck all the previous steps.

express app

Begin Coding

Open the folder article-app in your favourite text editor and begin coding. Open app.js file. It may seem quite heavy for you. But it is not.

With this require method, we are including express module into our project. If you open the package.json file, you will see

all the dependencies are listed there.

To properly include a dependency in your project, the module must be declared in your package.json file and then you should run npm install in your terminal. After that, we can require that module into our project.

Remember we just run one npm install, in the beginning, thus we installed all of our modules. It is now properly downloaded into our node_modules folder. Let’s install one package we need now to query and connect with our database MongoDB. The name of the package/module is mongoose.

Installing mongoose via terminal

Run this command in your terminal at the root of your project. Please open a new terminal at the root of your project.

We are telling npm to install mongoose package and also instructing to write it as a dependency into our package.json. If you now open package.json, you will notice that mongoose has been included there.

Lets modify our home page. Open views/index.ejs file. Paste the following code. I expect you that you know HTML.

You can see we are including one JavaScript file and css file. So you go to public/stylesheets/style.css and add these below code. I know its looking extremely bad. You can do your own styling.

Now you should understand that anything in our public directory, we have it in our views files. We included our script file

So let’s open the public/javascripts folder, and create a file named script.js

Refresh the page at  http://localhost:3000/, you should see like this below image.

Express Nodejs app

Understanding app.js file

Actually, we are telling express to serve the public folder as our static assets in our app.js file. We are doing through this. The code is already written by express generator for you.

Now we will connect with our database using mongoose

Connecting with MongoDB using mongoose

In the app.js file include these lines just after the requiring the body-parser

Remember that initially, we started our mongod. Now we are connecting with our local MongoDB. Generally, MongoDB runs on the port 27017.

Look at the connection string, with this, we are automatically creating one database named article.

Now we will create our Posts collection in our article database. A collection in MongoDB is similar to a table in SQL database.

Creating our Schema and Model using Mongoose

Using mongoose we are going to declare some rules which are called schema of our Posts collection.

Create models/Post.js and paste the following

The code is quite self-explanatory. We are giving the structure to our collection. Each document of the Post collection will have three fields those are name, article, timestamp.

Creating our first REST API endpoint

Now we are going to create one end point to save our data into our database. To do that please open your routes/index.js file. Your index.js file should now like this.

Let’s change the title of our home page. Just change index.js file to this.

Now if we refresh our page in the browser, we will not see any change. Because we have changed our code on the server side. So we need to restart our node server. You can do this by stopping the terminal (the terminal you ran npm start) by Ctrl+C

Then you need to run the server again by npm start. Now you should see that the tile of the app has been changed to “Article App”

Installing Nodemon using npm (Node Monitor)

It is irritating to restart our server each time when we make changes to our server code. So we are going to install a package called nodemon globally. Nodemon will intelligently restart our server whenever we make changes to it.

As we installed it with the global flag. The command nodemon is accessible throughout our system. Now we will start our server with nodemon.

Run the nodemon command in the root of your project

You should see the result like this one. Now we can refresh our web page and work without restarting the server. the work will be done by nodemon.

Now add this code just after the home page get route. Please read the comments.

Basically, here we are getting the data from the client and trying to save to save to the Post collection of our article database.

Let’s make post request from client using Fetch

We are going to use HTML5 Fetch API to do our post request. We are not going to use old XLMHttpRequest.

To do this open, public/javascrpts/script.js and add the following code

Now go to your web page and refresh. Open the dev console. Write your name and article and hit the save button.

You should see a message saying

{error: false, message: "Article Saved"}

If not, then let me know in the comments section. I will surely help you out.

Congratulations!

You are able to send data from the client side. Your nodejs server getting that data from the client. You are saving it to the MongoDB. That is wonderful.

Let’s display the data. To do this we need little bit modification in routes/index.js  file and in views/index.ejs file.

Serving the data from the server to the client

Open routues/index.js and change the according to the following code.

We will query the database in our get method of the homepage and send all the data to the client. We will do it before rendering. As I said earlier, in the render method, we can pass data as the second argument. That data will be available in our views/index.ejs file.

Understanding EJS templating

Open views/index.ejs file and modify it like below. You can write EJS in between  <% // your ejs code %>
I chose EJS as the templating engine because you can write javascript here. You do not need to learn a separate templating engine to get started with nodejs.

Below we are checking if the posts data is available. If it is available then we looping over the content of the posts.

Now if you refresh our web page, we can add our posts. Mine looks like this.

Mongodb Express Nodejs App

Yahoo!

Our app is complete. Though It is terribly bad looking but we learned a lot. Next steps to follow, please go to

ExpressJs Docs  and Mongoose Docs to learn more. If you are stuck at any step, then let me know in the comments. I will try to update this article. Thank you for following this.

You can get the FULL SOURCE CODE AT MY GITHUB. Just clone the repo and run npm install and npm start to see it in working.

17 thoughts on “Step by step tutorial NodeJs ExpressJs MongoDB App for Beginners (April 2017)

  1. It is the best time to make a few plans for the future and
    it is time to be happy. I have read this submit and if I
    may I desire to suggest you some attention-grabbing issues or tips.
    Perhaps you could write next articles regarding this
    article. I desire to read more issues about it!

  2. Installing mongoose via terminal is not working.
    even if i am in the root directory and opening terminal from there, after i insert the command it says “The filename, directory name, or volume label syntax is incorrect.”

      1. yes, i have even checked my node version as you have shown above.
        FYI its v6.10.2
        all the steps were going well then, this mongoose thing stopped working! 🙁

  3. Those of you, who are facing the same problem as me with “install mongoose via terminal ” and you getting a message like this — > “The filename, directory name, or volume label syntax is incorrect.”
    Just go to the root folder of your project (the folder whichcontains app.js and package.js files) and run cmd from the and just type
    ” npm install mongoose –save ”
    in the terminal. that should do it.
    thanks

  4. In your last part of the tutorial you modify the code of index.ejs file. Here i am getting a error when running the article app that says ” post is not defined ” what will be the solving approach plz let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *