Subscribe via RSS Feed

Web Application with Highchart.js, Node.js, Express.js and MongoDB(Mongo-JS Module)

June 3, 2013 3 Comments



HighChart Graph

This application is another proof of concept towards make a web application for graph generation  with Javascript based Web Server.

In this application we have used following tools and technologies -

1> Node.js for server side development

2> Rest based web service creation with express.js

3> Database – MongoDb

4> Node.js MongoDb Module Extention (mongojs)

5> Highchart.js for Graph generation through Asynchronous call (Ajax)

6> Using Cross-Domain policy to access REST service from Node.js to Ajax Call

We have created a Proof of Concept with Javascript based web server, where we have focused on dealing with NoSql (MongoDB) with javascript based framework Node.js.

Our initial code can be downloaded here.

Architecture at a glance -

HighChartjs NodeJs MongoDB

So here are the steps -

Installation -

A> Download and install Node.js from here.

B> To Develop the application we need to install mongojs module for Node.js

Command – npm install mongojs (should be connected to internet)

C> We need to install express.js for node.js

Command – npm install express  (should be connected to internet)

Server Application

Configuration Code -

Now, we will try to describe the code portion -

 
var application_root = __dirname,
    express = require("express"),
    path = require("path");

Here we have initialised the express.js within javascript variables in respect of Node.js concept.

 
var app = express();

Here we have initialised the express web server in app variable.

var databaseUrl = "faodb"; 
var collections = ["seeds"]
var db = require("mongojs").connect(databaseUrl, collections);

Here we have made the connection to the mongodb database using the Node.js mongojs module extension library.

 
// Config

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

Here we have made the configuration related to express.js
javascriptnosqlbook

Rest Services Code -

 
app.get('/api', function (req, res) {
  res.header("Access-Control-Allow-Origin", "*"); // Configuration for Cross-Domain-Policy
  res.send('Our Sample API is up...');
});

Here we have made our first REST based web service and tested whether the express.js is up.

Our sample api will be  - http://127.0.0.1:1212/api (Get Method)

 
app.get('/getseeddata/:seedname', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    seed = req.params.seedname;
	db.seeds.find({seedname:seed}, function(err, seeds) {
	if( err || !seeds) console.log("No seeds found");
	  else 
	{
		res.writeHead(200, {'Content-Type': 'text/json'});
		seedscollection = seeds[0].seedprice;
		str = '[';
		//console.log(seedscollection);

		seedscollection.forEach( function(seed) {
		   str = str + '{"month":"'+ seed.mmonth + '","price":"'+ seed.price +'"},';
		});
		str = str.substring(0,str.length-1)
		str = str + ']';
		res.end(JSON.stringify(str));
	}
  });
});

Here we have created another REST api to get price information for particular seed from seeds collection and so have done the mongojs query.

Our sample api will be  - http://127.0.0.1:1212/getseeddata/Arachide (Get Method)

Now we have to run node appmongodbhighchart.js from command shell to start the node server.

Client Application

Code Explanation for Highchart -

<script type="text/javascript">
    var myAjaxChart;
    var mydata = []; // Javascript Array Declaration
$(document).ready(function () { 

$("#seedselect").change(function() { // On change event of HTML Select Control
    mydata = [];
    requestData($(this).val()); // Parameterised Function calling for Ajax and Highchart Initiation
});

function requestData(data) {
$.ajax({
    url: 'http://localhost:1212/getseeddata/'+data, // Node.js Server REST Call
    type: "GET",
    dataType: "json",
    success: function(seed) {
        var jsonobj = seed;
        var obj = jQuery.parseJSON(jsonobj);
        for(i=0;i<obj.length;i++)
        {
            mydata.push(parseInt(obj[i].price)); // Filling of Array after Ajax Call
        }
        // Initialising the Highchart Object within the success callback
        //Chart
        var options ={
            chart: {
            renderTo: 'container', // Initialising the DIV with Highchart Object
            type: 'line',
            marginRight: 130,
            marginBottom: 25,
         },
         // Other Highchart Properties
         title: {
           text: 'Price Data',
           x: -20 //center
         },
         xAxis: {
         },
         yAxis: {
              title: {
              text: 'Price (Rs)'
         },
         plotLines: [{
              value: 0,
              width: 1,
              color: '#808080'
        }]
     },
     tooltip: {
             valueSuffix: 'Rs'
     },
     legend: {
           layout: 'vertical',
           align: 'right',
           verticalAlign: 'top',
           x: -10,
           y: 100,
           borderWidth: 0
      }
      ,
      series: [{
           name: 'Price',
           data: mydata  // Here the previously populated javascript array will be initialised in data parameter
      }],
     };
     var chardata = new Highcharts.Chart(options);
   },
   cache: false
  });
 }
});

Sign Up to read the rest of the content

Email will be used only for updates of our site

No Thanks