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

HighChart Graph

We previously posted an aricle on Web Application with Highchart.js, Node.js, Express.js (version 3) and MongoDB(Mongo-JS Module).This time we updated that same for Express 4.This application is a 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 (Express 4)

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 from 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

var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
  var bodyParser = require('body-parser');
  app.use(bodyParser.urlencoded({ extended: true }));
  var methodOverride = require('method-override');
  app.use(express.static(path.join(application_root, "public")));
  var errorhandler = require('errorhandler');

Here we have made the configuration related to express.js

Rest Services Code –

app.route('/api').get(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  – (Get Method)

app.route('/getseeddata/:seedname').get(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");
		res.writeHead(200, {'Content-Type': 'text/json'});
		seedscollection = seeds[0].seedprice;
		str = '[';

		seedscollection.forEach( function(seed) {
		   str = str + '{"month":"'+ seed.mmonth + '","price":"'+ seed.price +'"},';
		str = str.substring(0,str.length-1)
		str = 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  – (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) {
    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);
            mydata.push(parseInt(obj[i].price)); // Filling of Array after Ajax Call
        // Initialising the Highchart Object within the success callback
        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

If you find this article helpful, you can connect us in Google+ and Twitter.

1 thought on “Web Application with Highchart.js, Node.js, Express.js and MongoDB(Mongo-JS Module) – Updated for Express 4

Leave a Reply

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