Building Web Applications Using Node.js - Part Four

Before reading this article, I would recommend that you read my previous articles.
In my previous two articles, I explained,
  • How to start working with Node.js Web Application.
  • How to initialize a Node.js project.
  • About Package.JSON.
  • Express Framework.
  • How to use "npm start" command.
  • Using HTML Templates.
  • Bower.
  • Templating Engine.
  • Navigation.
  • Routing.
  • Rendering.
In this article, we will connect this Web Application to MongoDB database and fetch the data from the database, using this web application. Subsequently, I will explain how can we bind that data to Webpage.
 
If you see my previous article of this series, you will find I was repeating my navMenu code in each and every routing code. Thus, before connecting this Application to the database, I am removing that code and writing a route function. In it, I will pass navMenu variable, which is as follows.
 
articlesRoute.js

 
 
I have created one function --  a_router which takes and then returns articleRouter. In the previous article, I was exporting articleRouter. Now, you can see I am exploring my new function - a_router.
 
Note

Do not forget the things, mentioned below, else you will get an error.
  • Do not forget to return the value from router function. 
  • Do not forget to export the new router function.
  1. var express=require('express');  
  2.   
  3. var articlesRouter=express.Router();  
  4. var a_router=function(navMenu){  
  5.     articlesRouter.route("/")  
  6.         .get(function(req,res){  
  7.             res.render('articles', {  
  8.                 title:'Articles',  
  9.                 menu:navMenu  
  10.             });  
  11.         });  
  12.         return articlesRouter;  
  13. }  
  14.       
  15. module.exports=a_router;  
projectsRoute.js
  1. var express=require('express');  
  2.   
  3. var projectsRouter=express.Router();  
  4. var p_router=function(navMenu){  
  5.     projectsRouter.route("/")  
  6.         .get(function(req,res){  
  7.             res.render('projects', {  
  8.                 title:'Projects',  
  9.                 menu:navMenu  
  10.             });  
  11.         });  
  12.         return projectsRouter;  
  13. }  
  14. module.exports=p_router;  
booksRoute.js 
  1. var express=require('express');  
  2.   
  3. var booksRouter=express.Router();  
  4. var b_router=function(navMenu){  
  5.     booksRouter.route("/")  
  6.         .get(function(req,res){  
  7.             res.render('books', {  
  8.                 title:'Books',  
  9.                 menu:navMenu  
  10.             });  
  11.         });  
  12.         return booksRouter;  
  13. }  
  14.       
  15. module.exports=b_router;  
contactRoute.js
  1. var express=require('express');  
  2.   
  3. var contactRouter=express.Router();  
  4. var c_router=function(navMenu){   
  5.     contactRouter.route("/")  
  6.         .get(function(req,res){  
  7.             res.render('contact', {  
  8.                 title:'Contact Us',  
  9.                 menu:navMenu  
  10.             });  
  11.         });  
  12.         return contactRouter;  
  13. }  
  14. module.exports=c_router;  
Now, from app.js, you have to pass navMenu, as shown below.
 
 
 
In the code, mentioned above, you can see how I am passing navMenu from app.js to the route files. Complete app.js code is shown below.

app.js
  1. var express=require('express');  
  2. var app=new express();  
  3. var port=3000;  
  4. app.listen(port,function(err){  
  5.     if(typeof(err)=="undefined"){  
  6.         console.log('Your application is running on : '+ port+' port');  
  7.     }  
  8. });  
  9. var navMenu=[  
  10.                 {href:'/articles',text:'Articles'},  
  11.                 {href:'/projects',text:'Projects'},  
  12.                 {href:'/books',text:'Books'},  
  13.                 {href:'/Contact',text:'Contact Us'}  
  14.            ];   
  15.   
  16. app.use(express.static('public'));//making public directory as static diectory   
  17.   
  18. app.set('views','./src/views');   
  19.   
  20. app.set('view engine','ejs');  
  21. var articlesRouter=require('./src/routes/articlesRoute')(navMenu);  
  22. var projectsRouter=require('./src/routes/projectsRoute')(navMenu);  
  23. var booksRouter=require('./src/routes/booksRoute')(navMenu);  
  24. var contactRouter=require('./src/routes/contactRoute')(navMenu);  
  25.   
  26. app.use('/articles',articlesRouter);  
  27. app.use('/projects',projectsRouter);  
  28. app.use('/books',booksRouter);  
  29. app.use('/contact',contactRouter);  
  30.   
  31. app.get('/',function(req,res){  
  32.     res.render('index', {  
  33.         title:'Node.js By Sourabh Somani',  
  34.         menu:navMenu  
  35.     });  
  36. });  
Now, let's start binding the data from MongoDB. If you are new to MongoDB, follow the steps, mentioned below to setup your MongoDB.
  1. Download MongoDB from the official MongoDB Website.
  2. After downloading the setup, install MongoDB.
  3. Subsequently, create following folder "C:\data\db".
  4. Now, open the command prompt and go to the folder, mentioned below using cd command.
    cd C:\Program Files\MongoDB\Server\<version_number>\bin
  5. Now, type Mongod command. This is mongod Server. By using it, your Server will be on and some files will be installed in C:\Data\db folder.
  6. By default, MongoDB Server will start at port 27017.



  7. Now set environment variable in your system for C:\Program Files\MongoDB\Server\<version_number>\bin because for run mongod server we won't need to visit this path again and again.
Now to work with mongodb you need to start mongod server. To start that just use mongod command in command prompt and minimize command prompt.
 
After starting mongod server, open one more command pormpt and type the mongo command; by using that command you will be connected to the mongodb server, like the following.


 
Now, to check the list of the database you have in my MongoDB Server, you can use "show dbs" command.



Now, I am going to create a database inside MongoDB. To create and use a database, we can use the command, mentioned below.
  1. use <Database_Name>  
I am going to create a database with the name "NodeDemoWebApp".

 

To check your currently selected database, use the command db.

 
 
Now, I am going to insert some data for the article, project and books. For this article, I am inserting from command line but in my upcoming articles, I will show you how can we insert, using HTML forms, where we will learn how to login, followed by insert update delete, but for this article, I am just going to bind the data from the database.
 
Insert the command, mentioned below, in the command prompt. 

Articles Data
  1. db.articles.insert(  
  2.     {  
  3.         "Title":"Introduction to Node.js",  
  4.         "ShortDescription":"In this article you will learn about Node.js",  
  5.         "LongDescription":"Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009",  
  6.         "CreatedDate":new Date(2016,11,12),  
  7.         "Author":"Sourabh Somani",  
  8.         "AuthorImageUrl":"http://goo.gl/OSA4m5",  
  9.         "Category":"Node.js",  
  10.         "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/013723AM.png"  
  11.     });  
  12. db.articles.insert(  
  13.     {  
  14.         "Title":"Introduction to C#",  
  15.         "ShortDescription":"In this article you will learn about C#",  
  16.         "LongDescription":"C# (pronounced “see sharp” or “C Sharp”) is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002.",  
  17.         "CreatedDate":new Date(2016,11,08),  
  18.         "Author":"Mahesh Chand",  
  19.         "AuthorImageUrl":"http://goo.gl/8JJlPP",  
  20.         "Category":"C#",  
  21.         "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/051542AM.png"  
  22.     });  
  23. db.articles.insert(  
  24.     {  
  25.         "Title":"Introduction to Java Script",  
  26.         "ShortDescription":"In this article you will learn about Java Script",  
  27.         "LongDescription":"JavaScript is the programming language of HTML and the Web.",  
  28.         "CreatedDate":new Date(2016,10,08),  
  29.         "Author":"Sunny Sharma",  
  30.         "AuthorImageUrl":"http://goo.gl/fscpza",  
  31.         "Category":"Java Script",  
  32.         "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/054636AM.png"  
  33.     }  
  34. );  
Now, we will bind this data to articles page. To bind the data from MongoDB database, just follow the steps, mentioned below..

Step 1 


First, downlaod MongoDB package from npm., using the command, mentioned below.

 
 
After downloading MongoDB package, you can use the object of this package, using the code, mentioned below.
  1. var mongodb=require('mongodb').MongoClient;  
Note

In the code, mentioned above, MongoClient should be in title-case and this is also not a function.
 
To fetch the data from the database, you can write the code, mentioned below, inside articlesRoute.js file.
  1. var url='mongodb://localhost:27017/NodeDemoWebApp';  
  2.             mongodb.connect(url,function(err,db){  
  3.                 var collection=db.collection('articles');  
  4.                 collection.find({}).toArray(function(err,results){  
  5.                     res.render('articles', {  
  6.                         title:'Articles',  
  7.                         menu:navMenu,  
  8.                         article:results  
  9.                     });  
  10.                 });  
  11.             });   
Explanation of the code mentioned above.
  • I have created a URL to connect with MongoDB database where mongodb:// is a protocol definition to connect MongoDB.
  • localhost:27017/NodeDemoWebApp is a URL, which connects to NodeDemoWebAppDatabase, which we have created.
  • mongodb.connect() is a function available in MongoDB package, which is used to connect through the database.
  • When connection is done then mongodb.connect() function calls a callback function which contains an error and a database object. Hence, in the code, mentioned above, err is an Error and db is the database connection object.
  • Now, after connecting to the database, I am going to create an object for the articles collection.
  • Now, in the next line, collection.find({}) function gets all the data from the articles and then I am converting all the data into an array, using toArray() function.
  • After converting the data into an array, now it will call a callback function, which will take two parameter err, which means error and result, where we will get the complete result of articles in an array format. 
  • After I am rendering my page, this time I am also binding the articles.
I am also writing the complete code for articlesRoute.js, which is shown below.
  1. var express=require('express');  
  2. var mongodb=require('mongodb').MongoClient;  
  3. var articlesRouter=express.Router();  
  4. var a_router=function(navMenu){  
  5.     articlesRouter.route("/")  
  6.         .get(function(req,res){  
  7.             var url='mongodb://localhost:27017/NodeDemoWebApp';  
  8.             mongodb.connect(url,function(err,db){  
  9.                 var collection=db.collection('articles');  
  10.                 collection.find({}).toArray(function(err,results){  
  11.                     res.render('articles', {  
  12.                         title:'Articles',  
  13.                         menu:navMenu,  
  14.                         articles:results  
  15.                     });  
  16.                 });  
  17.             });  
  18.         });  
  19.         return articlesRouter;  
  20. }  
  21.       
  22. module.exports=a_router;  
Now, I am binding the article data to the articles view page, which means articles.ejs file.
  1. <!--Binding Articles Data-->  
  2.         <%for(var p=0;p<articles.length;p++){%>  
  3.             <div class="row">  
  4.                 <div class="col-md-3">  
  5.                     <a href="#" class="text-center">  
  6.                             <img class="img-responsive author-img" src="<%=articles[p].AuthorImageUrl%>" alt="">  
  7.                     </a>  
  8.                 </div>  
  9.                 <div class="col-md-9">  
  10.                     <h2><%=articles[p].Title%></h2>  
  11.                     <h5>  
  12.                         <i class='glyphicon glyphicon-folder-open'></i> <span style='margin:0 10px 0 5px;'><%=articles[p].Category%></span>  
  13.                         <i class='glyphicon glyphicon-calendar'></i> <span style='margin:0 10px 0 5px;'><%=articles[p].CreatedDate.toDateString()%></span>  
  14.                     </h5>  
  15.                     <h5>  
  16.                         <i class='glyphicon glyphicon-user'></i> <a href="javascript:void(0)" style='margin:0 10px 0 5px;'><%=articles[p].Author%></a>  
  17.                     </h5>  
  18.                     <p><%=articles[p].ShortDescription%></p>  
  19.                     <a class="btn btn-primary" href="#">Read Article <span class="glyphicon glyphicon-chevron-right"></span></a>  
  20.                 </div>  
  21.             </div>  
  22.             <hr/>  
  23.         <%}%>  
After binding, run the code and you will get the output, as shown below.
 
 

Conclusion

In this article, we have seen how to connect our Node.js Web Application to MongoDB, fetch the data, and bind the data to our Application.
 
What is next?

In my next article, I will show you how can we create registration page and login. I will show you how to authenticate a user in Node.js. Subsequently, I will create a complete page to submit the article, project, and blog. Afterwards, we will create a contact form and many more.
 
Download Source Code

You can download the source code from the link Node.js web application project.

<<Previous Article                                                                                                                               Next Article>>


Similar Articles