Using AngularJS with MongoDB
This article shows you how to use a MongoDB NoSQL database with the AngularJS and Node JS frameworks. Together, these three technologies make it possible to develop professional large-scale web applications that require a lot of scalability, both from a code-base and data perspective.
You often see how to learn each technology separately on the Web, which is important but only part of the equation. As of late, the use of MongoDB with the Angular, Node, and Express frameworks has become very popular among development shops for delivering smoother application user experiences to their clients.
Languages such as Java, .NET, and Python are still used for industrial applications because of their extensive libraries, but Angular and Node are fast becoming choices for developing web applications on all levels.
In the past, JavaScript lacked the capacity for doing code-bases that implemented true OO concepts such as inheritance, polymorphism, and encapsulation. Angular has been doing the most to bridge this gap through using the MVC OO model of programming architecture commonly used by Java and .NET MVC frameworks.
Also lacking with JS frameworks was the capability to create native database components for integrating with databases. So there was the need for always passing the data using AJAX to a back-end service developed with Java, or .NET web service frameworks such as WCF and JAX-RS. Node has now taken center stage to take care of this for JS frameworks because it is also a scripting framework.
So how can Node implement native database objects for working with databases? You will find out in this article, but you should remember that Node was built on top of C++, giving it the same advantage of Python, which is built on top of Objective C. Because these scripting languages are built on top of OO languages, they can create native objects for doing back-end integration with databases and other services such as FTP and others.
Mongo JS
Mongo JS is Node's answer for allowing any JS framework using Node as a back-end server to also interact with a MongoDB database. To install the mongojs module, do an npm command from the shell:
npm install mongojs
The next step is to configure Node to handle the request data from a web form and insert this data into MongoDB.
For the form part of this example, I refer you to my article titled “AngularJS Fundamental Concepts for Building Web Applications: Part 4” on InformIT.com.
Copy the code from this article into a page called register.htm. To simplify it, remove the password boxes from the code so that only the Name and Email form fields are left.
You will add the http module code to this page soon, but your Node sever JS page should now look like this:
var http = require('http'); var fs = require('fs'); var path = require('path'); var url = require('url'); var qs = require('querystring'); var mimeTypes = { "html": "text/html", "jpeg": "image/jpeg", "jpg": "image/jpeg", "png": "image/png", "js": "text/javascript", "css": "text/css"}; var databaseUrl = "test"; var collections = ["testData"] var db = require("mongojs").connect(databaseUrl, collections); var server = http.createServer(function onRequest(request, response) { var urlParts = url.parse(request.url); var fullPath = urlParts.pathname; var page = 'pages' + urlParts.pathname; var jsonUserOject = ''; if (fullPath == "/post") { var userName = ''; request.on('data', function(chunk) { jsonUserObject = JSON.parse(chunk.toString()); userName = jsonUserObject.name; userEmail = jsonUserObject.email; db.testData.insert({name: userName, email: userEmail}, function(err, testData) { if( err || !testData) console.log("Unable to add user"); }); }); } var mimeType = mimeTypes[path.extname(page).split(".")[1]]; fs.exists(page, function fileExists(exists) { if (exists) { response.writeHead(200, mimeType); fs.createReadStream(page).pipe(response); } else { response.write('Page Not Found'); response.end(); } }); }).listen(3300);
Outside of the normal Node server scaffolding code for handling requests, mongojs is required, and a couple of parameters are passed to initialize the db object.
The first object is the database URL, and this parameter is just the name of the db if using the default MongoDB setup. If using a different setup, you have to include the port number and user name and password for the db (if they exist) in this string.
The second parameter is the name of one or more collections in the db that you want to work with. Now you can use the db variable in Node just as you can from the Mongo shell. The syntax is the same because mongojs actually interacts with the shell, but serves as a wrapper for MongoDB.
To add the record from the form in the register.htm page, look for the path that has the value 'post'. If you get a request with this path, you know it is coming from the http module in register.htm.
From here, parse out the body of the request, which is a JSON string. To deserialize the string to a JSON object, the JSON.parse() method is used.
Now it is just a matter of using the JSON object, userObject, to populate the insert values for the MongoDB insert method, and that's it!
I have seen different ways of doing this on the Web, but most were hard to follow and included an extra layer, namely Express.js. This method is more direct, and Express.js is not necessary.
You can easily handle all your app's CRUD operations right within Node by using Restful syntax for the URL calls.
To make the form work, add the following AngularJS script code below your form:
<script> angular.module('formExample', []) .controller('ExampleController', ['$scope', '$http', function($scope, $http) { $scope.master = {}; $scope.update = function(user) { if ($scope.formx.$valid) { $scope.master = angular.copy(user); $http.post('http://localhost:3300/post', $scope.master ).success(function(data, status, headers, config) { alert("Success!") }).error(function(data, status, headers, config) { alert("Error"); }); } }; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); }]); </script>
Most of the code is already there with the example form, but it does not work unless you replace it with the whole block shown here because it includes the correct URL and passes in the $http module variable into the controller.