Before reading this article, I would recommend that you read my previous articles.
- 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.
- var express=require('express');
-
- var articlesRouter=express.Router();
- var a_router=function(navMenu){
- articlesRouter.route("/")
- .get(function(req,res){
- res.render('articles', {
- title:'Articles',
- menu:navMenu
- });
- });
- return articlesRouter;
- }
-
- module.exports=a_router;
projectsRoute.js
- var express=require('express');
-
- var projectsRouter=express.Router();
- var p_router=function(navMenu){
- projectsRouter.route("/")
- .get(function(req,res){
- res.render('projects', {
- title:'Projects',
- menu:navMenu
- });
- });
- return projectsRouter;
- }
- module.exports=p_router;
booksRoute.js
- var express=require('express');
-
- var booksRouter=express.Router();
- var b_router=function(navMenu){
- booksRouter.route("/")
- .get(function(req,res){
- res.render('books', {
- title:'Books',
- menu:navMenu
- });
- });
- return booksRouter;
- }
-
- module.exports=b_router;
contactRoute.js
- var express=require('express');
-
- var contactRouter=express.Router();
- var c_router=function(navMenu){
- contactRouter.route("/")
- .get(function(req,res){
- res.render('contact', {
- title:'Contact Us',
- menu:navMenu
- });
- });
- return contactRouter;
- }
- 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
- var express=require('express');
- var app=new express();
- var port=3000;
- app.listen(port,function(err){
- if(typeof(err)=="undefined"){
- console.log('Your application is running on : '+ port+' port');
- }
- });
- var navMenu=[
- {href:'/articles',text:'Articles'},
- {href:'/projects',text:'Projects'},
- {href:'/books',text:'Books'},
- {href:'/Contact',text:'Contact Us'}
- ];
-
- app.use(express.static('public'));
-
- app.set('views','./src/views');
-
- app.set('view engine','ejs');
- var articlesRouter=require('./src/routes/articlesRoute')(navMenu);
- var projectsRouter=require('./src/routes/projectsRoute')(navMenu);
- var booksRouter=require('./src/routes/booksRoute')(navMenu);
- var contactRouter=require('./src/routes/contactRoute')(navMenu);
-
- app.use('/articles',articlesRouter);
- app.use('/projects',projectsRouter);
- app.use('/books',booksRouter);
- app.use('/contact',contactRouter);
-
- app.get('/',function(req,res){
- res.render('index', {
- title:'Node.js By Sourabh Somani',
- menu:navMenu
- });
- });
Now, let's start binding the data from MongoDB. If you are new to MongoDB, follow the steps, mentioned below to setup your MongoDB.
- Download MongoDB from the official MongoDB Website.
- After downloading the setup, install MongoDB.
- Subsequently, create following folder "C:\data\db".
- Now, open the command prompt and go to the folder, mentioned below using cd command.
cd C:\Program Files\MongoDB\Server\<version_number>\bin - 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.
- By default, MongoDB Server will start at port 27017.
- 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.
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
- db.articles.insert(
- {
- "Title":"Introduction to Node.js",
- "ShortDescription":"In this article you will learn about Node.js",
- "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",
- "CreatedDate":new Date(2016,11,12),
- "Author":"Sourabh Somani",
- "AuthorImageUrl":"http://goo.gl/OSA4m5",
- "Category":"Node.js",
- "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/013723AM.png"
- });
- db.articles.insert(
- {
- "Title":"Introduction to C#",
- "ShortDescription":"In this article you will learn about C#",
- "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.",
- "CreatedDate":new Date(2016,11,08),
- "Author":"Mahesh Chand",
- "AuthorImageUrl":"http://goo.gl/8JJlPP",
- "Category":"C#",
- "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/051542AM.png"
- });
- db.articles.insert(
- {
- "Title":"Introduction to Java Script",
- "ShortDescription":"In this article you will learn about Java Script",
- "LongDescription":"JavaScript is the programming language of HTML and the Web.",
- "CreatedDate":new Date(2016,10,08),
- "Author":"Sunny Sharma",
- "AuthorImageUrl":"http://goo.gl/fscpza",
- "Category":"Java Script",
- "CategoryImage":"http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/MinorCatImages/054636AM.png"
- }
- );
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.
- 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.
- var url='mongodb://localhost:27017/NodeDemoWebApp';
- mongodb.connect(url,function(err,db){
- var collection=db.collection('articles');
- collection.find({}).toArray(function(err,results){
- res.render('articles', {
- title:'Articles',
- menu:navMenu,
- article:results
- });
- });
- });
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.
- var express=require('express');
- var mongodb=require('mongodb').MongoClient;
- var articlesRouter=express.Router();
- var a_router=function(navMenu){
- articlesRouter.route("/")
- .get(function(req,res){
- var url='mongodb://localhost:27017/NodeDemoWebApp';
- mongodb.connect(url,function(err,db){
- var collection=db.collection('articles');
- collection.find({}).toArray(function(err,results){
- res.render('articles', {
- title:'Articles',
- menu:navMenu,
- articles:results
- });
- });
- });
- });
- return articlesRouter;
- }
-
- module.exports=a_router;
Now, I am binding the article data to the articles view page, which means articles.ejs file.
- <!--Binding Articles Data-->
- <%for(var p=0;p<articles.length;p++){%>
- <div class="row">
- <div class="col-md-3">
- <a href="#" class="text-center">
- <img class="img-responsive author-img" src="<%=articles[p].AuthorImageUrl%>" alt="">
- </a>
- </div>
- <div class="col-md-9">
- <h2><%=articles[p].Title%></h2>
- <h5>
- <i class='glyphicon glyphicon-folder-open'></i> <span style='margin:0 10px 0 5px;'><%=articles[p].Category%></span>
- <i class='glyphicon glyphicon-calendar'></i> <span style='margin:0 10px 0 5px;'><%=articles[p].CreatedDate.toDateString()%></span>
- </h5>
- <h5>
- <i class='glyphicon glyphicon-user'></i> <a href="javascript:void(0)" style='margin:0 10px 0 5px;'><%=articles[p].Author%></a>
- </h5>
- <p><%=articles[p].ShortDescription%></p>
- <a class="btn btn-primary" href="#">Read Article <span class="glyphicon glyphicon-chevron-right"></span></a>
- </div>
- </div>
- <hr/>
- <%}%>
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.