Single page Application with Angularjs, Minimalweb Node MVC and MongoDB

In this post, we have made a Single Page Application with Angularjs, Minimalweb Node MVC and MongoDB.

Brief Background

Lot of tutorial are already there in web regarding the MEAN (MongoDb,Expressjs,Angularjs and Nodejs) stack. Here we have followed the same path, except for the Express.js framework. We have used minimalweb framework for the server MVC.


Minimalweb is a simple web framework with node.js which has provision to support rest api and general http request/response. The framework will only support request/response handling through controller. The Model and Service related implementation will be needed to be done by user. The view can be attached in Configuration or can be injected from Controller.

Some features of the framework –

    • Get Method Handling
    • Post Method Handling
    • Post Method Handling with Upload
    • Limited set of REST Support (Upto Now)
    • Request Parameter Handling
    • Session Handling
    • Custom Middleware support at Request Processing Level
    • Central Request Interceptor Support
    • After Response Interceptor Support at Controller Level
    • Minimum caching support for static file serving
    • Routing configuration through JSON Array

More about the framework can be found in or in
github repository

Features of the SPA in this Article

        • Angular.js for client side development – Single Page Application (SPA)
        • Cross Domain Communication in between Angular.js and Node.js Application Server through Custom Middleware
        • Node.js for server side application development
        • Rest based web service creation with Minimalweb
        • Datastore – MongoDb
        • Node.js MongoDb Module Extention (mongojs)

Reader can download the complete source-code in GitHub.

Architechture at a nutshell

Angularjs Minimalweb Nodejs Mongodb


A> Download and install Node.js from here.
B> To Develop the application we need to install mongojs module for Node.js

npm install mongojs

C> We need to install minimalweb

npm install minimalweb

We have pushed the complete project in github and reader will find the package.json in server project, which is structured as –

"name": "minimalweb-mongo-integration",
"description": "Integration with mongodb and minimalweb",
"author": {
"name": "Piyas De",
"email": ""
"dependencies": {
"minimalweb": "^0.1.8",
"mongojs": "^0.18.1"

So, if reader run the command – [javascript]npm install[/javascript], all the related dependencies will be installed in “node_modules” folder within the application folder.

The Server Starting Point

This class will start the server with listening on some ip and host, connect to our route functionality and router configuration class. Additionally, here we can inject any middleware code for any request/response from this class.

The helper comment is inline within the code.

var minimalweb = require(‘minimalweb’);

// Need for routing functionality
var route = minimalweb.route;

//Need for logging functionality
var logger = minimalweb.logger;

//If we want to middlewares, here we have used middleware to have CORS functionality, described later
var corsMiddle = require(‘./server-middlewares/corsMiddleWare’); //declare the middleware
route.use(corsMiddle); //attach it to the actual route

// routing collection is aquired and send to route for request processing
var routeCollection = require(‘./routeCollection’).getRouteCollection().routeCollection;

//Final step – start the server
logger.log(‘server started’);

Now the middleware functionality

As we have used REST Api calling from the Angularjs application, which is hosted in different server, we needed to implement CORS in the Node.js Application Server. Now, within the framework, we have used custom middleware to implement the functionality. This middleware is responsible for the CORS handling for the server application. Reader can find more about custom middlewares in this section.

Code is below with inline comments –

var logger = require(‘minimalweb’).logger;
var corsFunction = function (req,res,next) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost"); // On same machine here, address
//will be different for other hosted client applications.
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
next(); // After validation for CORS, Framework will take care the request processing
module.exports = function(req,res,next) {
return corsFunction(req,res,next);

The Router configuration

All the path for GET and POST request should be configured in this collection. This is the central information repository, from which the router will be able to find the required controller for processing the request and response.We need to configure any of resources in project, which is responsible for request/response flow handling, through this class and as provided in json array structure. So we have a central configuration file, which is actually handling the flow of application with declarative structure.

var routeCollection =
format:"postdata", methodName:"insert"}

More information and documentation about the router collection configuration can be found in –

Controller Code

Controller is responsible for request and response processing with helper of business logic methods in this framework. Controllers in this framework, can be written in many ways, here we have adopted controller with methods. Below is the code with comments inline. Here we have shown only method related code snippet, for whole class code please refer to the

// Request to get the users from the datastore
MethodController.get = function(req,res) {
// Data Access methods and callback
userwork.getUser(function (err, userString) {
if (err) {
res.send(HTTPStatus.INTERNAL_SERVER_ERROR,’Internal Server Error’);
MethodController.setJson("{\"error\":\"No Such Data\"}");
console.log(‘content -‘+content);

// Request to insert the users in the datastore
MethodController.insert = function(req,res) {
// class, which is responsible for handling the POST Request body
var pf = new postForm(req,res,__dirname + ‘/../upload’);
pf.on(‘post’, function(req,res,fields, files) {
// Data Access methods and callback
userwork.insertUser(fields.mydata, function (err, contents) {
if (err) {
//res.end( "User not saved");
MethodController.setJson("{\"msg\":\"User not saved\"}");
else {
MethodController.setJson("{\"msg\":\"User not saved\"}");
logger.log(‘content -‘+content);

Data Access

Now the data access code, which is specific for mongodb datastore. Any datastore specific code can be injected in this framework. Code snippet from the data access class (The driver is related to mongojs library) –

//Access the collection
var users = db.collection(‘minimalwebusers’);

//Method to insert data in mongodb
function insertUser(jsonVar, cb) {
var jsonData = JSON.parse(jsonVar);{email:, password: jsonData.password, username: jsonData.username}, function(err, saved) {
if( err || !saved )
return cb(err,’Internal Server Error’);
return cb(null,JSON.stringify(saved));

//Method to get data from mongodb
function getUser(cb) {
users.find(function(err, usersrec) {
if( err || !usersrec)
return cb(err,’Internal Server Error’);
if (usersrec == ”)
return cb(null,JSON.stringify("[]"));
usersrec.forEach( function(user) {
str = str + ‘{ "name" : "’ + user.username + ‘","email" : "’+ +’"},’ ;
str = str.trim();
str = str.substring(0,str.length-1);
str = str + ‘]’;
return cb(null,str);

Flow of the Minimalweb framework (A diagram)

Minimalweb - MethodController - How it works

Now we will discuss Angularjs client part of the application.We had deployed the client part in Apache server.

Angular.js 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’];

/* Controller */
function UserListCtrl($scope, $http, $templateCache) {
var method = ‘POST’;
var inserturl = ‘’;//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);

$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 = ‘’;//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

Below is Angualrjs App Initiation for application which will be responsible for the behavior of DOM Elements in this web page.

 <html lang="en" ng-app="myApp"> 
 <body ng-controller="UserListCtrl">

We have referred the Angular Controller in above code – it will broadly control the behavior of the html fragments and components within the controller. We had shown the controller code previously.

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.

A little note –

We will attach the Testing for node.js modules and angular.js modules in our next articles. So watch the site for next articles within next few days.


While writing this article, we assumed that user have a knowledge over angular.js, node.js and mongodb.

Reader can download the complete source-code in GitHub.

May we expect a for the minimalweb mvc ?

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


2 thoughts on “Single page Application with Angularjs, Minimalweb Node MVC and MongoDB

Leave a Reply

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