Subscribe via RSS Feed

Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module)

June 25, 2013 51 Comments

Previously we have posted the communication for Developing Web Application with Node.js, Express.js and MongoDB (MongoJS module).

Current post is a proof of concept towards make a web application with Javascript based Web Server. This technological stack is popularly known as MEAN  Stack.

To make this possible, we have selected -

1> Angular.js for client side development – Single Page Application

2> Cross Domain Communication in between Angular.js and Node.js

3> Node.js for server side development

4> Rest based web service creation with express.js

5> Database – MongoDb

6> Node.js MongoDb Module Extention (mongojs)

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 and angular.js on client side.

Our initial code can be downloaded here.

Architecture at a glance -

Angularjs 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)

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 = "sampledb"; 
var collections = ["things"]
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.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

Here we have made the configuration related to express.js

Rest Services Code -

app.get('/api', function (req, res) {
  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.get('/getangularusers', function (req, res) {
	res.header("Access-Control-Allow-Origin", "http://localhost");
	res.header("Access-Control-Allow-Methods", "GET, POST");
        // The above 2 lines are required for Cross Domain Communication(Allowing the methods that come as Cross           // Domain Request
	db.things.find('', function(err, users) { // Query in MongoDB via Mongo JS Module
	if( err || !users) console.log("No users found");
		res.writeHead(200, {'Content-Type': 'application/json'}); // Sending data via json
		users.forEach( function(user) {
			str = str + '{ "name" : "' + user.username + '"},' +'\n';
		str = str.trim();
		str = str.substring(0,str.length-1);
		str = str + ']';
		res.end( str);
                // Prepared the jSon Array here

Here we have created another REST api to get all username from user collection and so have done the mongojs query.

Our sample api will be  - (Get Method)'/insertangularmongouser', function (req, res){
  console.log("POST: ");
  res.header("Access-Control-Allow-Origin", "http://localhost");
  res.header("Access-Control-Allow-Methods", "GET, POST");
  // The above 2 lines are required for Cross Domain Communication(Allowing the methods that come as Cross 
  // Domain Request
  var jsonData = JSON.parse(req.body.mydata);{email:, password: jsonData.password, username: jsonData.username},
       function(err, saved) { // Query in MongoDB via Mongo JS Module
           if( err || !saved ) res.end( "User not saved"); 
           else res.end( "User saved");

Here we have made a POST request to create an user via REST calling.

Our sample api will be  - Method)

// Launch server

We have made the server to listen at 1212 port.

Now run node appmongodbangular.js from command shell.

Angular.js part -

Below is the code in Angular Controller -

'use strict';

var myApp = angular.module('myApp', []); // Taking Angular Application in Javascript Variable

// Below is the code to allow cross domain request from web server through angular.js
myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];

/* Controllers */

function UserListCtrl($scope, $http, $templateCache) {

  var method = 'POST';
  var inserturl = 'http://localhost:1212/insertangularmongouser';// URL where the Node.js server is running
  $scope.codeStatus = "";
  $ = function() {
    // Preparing the Json Data from the Angular Model to send in the Server. 
    var formData = {
      'username' : this.username,
      'password' : this.password,
	  'email' :

	this.username = '';
	this.password = ''; = '';

	var jdata = 'mydata='+JSON.stringify(formData); // The data is to be string.

	$http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
            method: method,
            url: inserturl,
            data:  jdata ,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            cache: $templateCache
        success(function(response) {
		console.log("success"); // Getting Success Response in Callback
                $scope.codeStatus =;

        error(function(response) {
		console.log("error"); // Getting Error Response in Callback
                $scope.codeStatus = response || "Request failed";
	$scope.list();// Calling the list function in Angular Controller to show all current data in HTML
        return false;

  $scope.list = function() {
	  var url = 'http://localhost:1212/getangularusers';// URL where the Node.js server is running	
	  $http.get(url).success(function(data) {
		$scope.users = data;
          // Accessing the Angular $http Service to get data via REST Communication from Node Server 


Angular Template and HTML

 <html lang="en" ng-app="myApp">

We have referred the Angular Application in above code

 <body ng-controller="UserListCtrl">

We have referred the Angular Controller in above code

Search: <input ng-model="user">
<div class="span10">
    <!--Body content-->
    <ul class="users">
        <li ng-repeat="user in users | filter:user ">

We have used the ng-repeat tag to take the users data model from REST communication and shown in HTML

<form name="myform" id="myform1" ng-submit="save()">
        <legend>New User</legend>
            <div class="control-group">
                <center><input type="text" placeholder="User…" ng-model="username" size=50 required/></center>
                <center><input type="text" placeholder="Password…" ng-model="password" size=50 required/></center>
                <center><input type="text" placeholder="Email…" ng-model="email" size=50 required/></center>
         <div><center><button type="submit" >Save now...</button></center></div>

We have used the ng-submit tag to send the user data model from REST communication and sent to node server to save in MongoDB.

Reader can download the complete source-code in GitHub.

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

Enter your email address:Delivered by FeedBurner
  • Darryl Snow

    How do you run it? If you run node /server/appmongodbangular.js then you’ll run the server part /api on port 1212, but what about the client? Thanks

    • Piyas De

      We had tested the client code in a Apache Web Server – localhost and port 80. Also in the Article we have mentioned the handling of cross-browser issues.

      • Darryl Snow

        So the client and server are run separately?

        • Piyas De

          Yes. This is the case.

        • codedungeon

          Yes, this is the way all node based applications are running in general. You have a server component (runs on node) and a client component (runs in the browser)

  • Pingback: Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module) | Technical Blogs

  • Pingback: AngularJS Highlights: Week Ending 21 July 2013 | SyntaxSpectrum

  • Pingback: Concepts in Angular.js Application Development | Technical Blogs

  • Pingback: LEAN and MEAN (Mongodb ExpressJS AngularJS NodeJS) on CloudBees, OpenShift, Heroku and AppFog (draft) « /dev

  • codedungeon

    So why use mongojs library? just curious what it offers over native Mongo commands?

    • Piyas De

      We have tried to work with Node.js and MongoDB without using ORM wrapper like Mongoose and so this is the post with our POC with working with MongoJS

  • Pingback: Single Page Application with Angular.js, Node.js and NeDB (NeDB Module)

  • Mukesh Soni

    Can’t read the article on mobile due to the floating social icons on top

    • Piyas De

      We will review this – how to place the widget…

  • thecity2

    I use this same stack for my website (, but call it AMEN. ;)

  • Pingback: AngularJS Highlights: Week Ending 11 August 2013 | SyntaxSpectrum

  • Pingback: Aurélien Vecchiato (aurevec) | Pearltrees

  • Pingback: AngularJS Highlights: Week Ending 18 August 2013 | SyntaxSpectrum

  • Pingback: Best JavaScript Tutorials, Techniques, Plug-ins and Libraries

  • Vo Thanh Thang

    Thank alot for your project, but I still do not know how to run your project. How to config Apache web sever?, where to put your project folder?, where is the code of
    Cross Domain Communication in between Angular.js and Node.js?. I am newbie like a dummy. Thank so much

    • Piyas De

      Please install node.js and other modules as written in “Installation” section.

      Please google for Apache Web Server installation and put application in htdocs folder.

      Please go through the “res.header” section of node.js code in the post which is commented as Cross Domain Configuration.

      Please go through the above instruction and comment for any help required, that we can.

      • Vo Thanh Thang

        I put the server folder in C drive, import sampledb.json to Mongodb, put client folder in htdocs. After that, I run Mongo by git, then run appmongodbangular.js by window cmd: node c:serverappmongodbangular.js but it is not executed with no error alerted. So what is the problem?. Thanks

        • Piyas De

          Have you installed node.js in your machine?

          We have installed the node.js first in our machine. Then we have written the js file “appmongodbangular.js” in our system. And then run it with “node appmongodbangualr.js”. Can you share the error, which is there – in your command line console?…

          • Vo Thanh Thang

            Yes, I installed node.js window package dowloaded from

            No error, It is not run and no error. After I press Enter, nothing happenes in my command line console. I was wating for 5 minutes.

            But with the app.js file of MEAN Stack is ok, I can run it (

          • Piyas De


            See, after your feedback we have again gone through our application. It is running good. Our steps -

            1> Run mongodb from command prompt -

            2> Run “node appmongodbangular.js”
            It is running fine.

            3>put the client “angular” folder in httpdocs folder in xampp

            4> run “http://localhost/angular/angularnodeuser.html”

            in browser.

            That is all.

            Please look through the above instruction and let us know.

  • Diego Vieira

    impossible to read this article. the top slider keeps making the text going up and down.

    • Piyas De

      Thanks for feedback. Point taken. Made the slider auto-scrolling off. After loading of the slider, the page up-down behavior will not happen.

      • Diego Vieira

        Thanks much! ;)

  • Katsumoto

    users.forEach( function(user) {
    str = str + '{ "name" : "' + user.username + '"},' +'n';
    str = str.trim();
    str = str.substring(0,str.length-1);
    str = str + ']‘;
    res.end( str);
    // Prepared the jSon Array here

    This is a joke??

    • Piyas De

      What do you want to understand here? Here we have made the json array and send to browser client i.e. angular.js framework to parse it. Also this article is is a poc of the whole stack and it is running.

      • David Virebayre

        He wants to understand why you’re building the response that way, instead of making an array and then serialising it, as you probably should.

  • Pingback: Handling GET requests with Google DART, Node.js and MongoDB

  • bcs

    Can you please give an example on how to connect to Oracle Database using


    • Piyas De

      OK.We will work on that. Issue is, we do not use oracle for our applications. Once we are ready with a database server, we will post on this and get back to you.

      • bcs

        Thank you

  • Pingback: Single Page Application with Angular.js, Node.j...

  • Vi

    I am getting below error while installing mongojs module.

    MSBUILD : error MSB3428: Could not load the Visual C++ component “VCBuild.exe”.
    To fix this, 1) install the .NET Framework 2.0 SDK, 2) install Microsoft Visua
    l Studio 2005 or 3) add the location of the component to the system path if it
    is installed elsewhere. [C:Usersvinay_000angular-phonecatnode_modulesmong

    Do I really need to install these additional components in order to make this work?

    • Piyas De


      As the issue is seen, somehow your node.js installation is not correct. Actually if node.js is build from source, then it will be fine. In my linux box, I have built the node.js with GC++ and all other installation were fine. Generally for some node.js modules, the above type of issues are seen. So I have switched my development of node.js applications from windows to linux.


  • Pingback: Express 4.x / AngularJS / Mongo Example « james young

  • Pingback: /dev | MEAN 2

  • pixelBender67

    your code is outdated, express has changed. It would be great if you updated the code to work with express v4

    • Piyas De

      Thanks for suggestion. We are currently working on express 4 and we will update all the code-base for Express 4 within next few days.

  • samir

    I cant download project from GitHub. Can you please provide full url of GitHub Project.

  • Pingback: Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module) - (Updated for Express 4) - Technical Blogs : Technical Blogs

  • Daniel Baah

    I went through multiple angular / node tutorials… and this is the only one that I could get to work…


  • Majid Lotfi

    HI, Thank you for this tutorial, I download it, went to the server folder and did :

    app.configure(function () {
    TypeError: Object function (req, res, next) {
    app.handle(req, res, next);
    } has no method ‘configure’
    at Object. (C:UsersalotfinodeJSNodeMongoDBAngularserverappmongodbangular.js:12:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

    at node.js:906:3

    Please your help is appreciated.