Introduction
In this article we look into how simple or easy it is to write an application using Mean stack. For understanding this article or to write your first Mean stack application you will need basic understanding of Javascript. In this article we go step by step and build our first application using MongoDB (Back-End), Express.js (Middle-Layer), Angularjs (Front-End) and Node.js together know has MEAN.
I would like to get feedback on this article. Please feel free to share your comments or you can also email me atshettyashwin@outlook.com. If you like this article, please don't forget to rate it.
Using the code
Let’s get started. First and most important thing you need to install Node.js. You can download Nodejs from https://nodejs.org/en/ based upon your OS and processor (64 / 32 bit) choose the correct installer. Installer wizard will guide you with correct steps. To verify if you have successfully installed your node.js open a Command window (cmd in Windows and Terminal in Mac). Type
Node --version
If you are able to see version detail than you have successfully installed your Node.js. If your command window is not able to recognize this command than just verify that physical address of the Nodejs installed folder is been added in System Environment Variable Path (In Windows). If Node.js path is not added in the Path variable than please add the same. Close the command window and open a new one. You should be able to see the version detail now after above command is been executed.
Our next step is to get Express.js. For doing so I would suggest using express-generator. Express-generator will get you boilerplate code for getting you started. You can also look for any other code generator at NPM website. But for now let get started with express-generator. Create a working folder on local hard drive. Let’s assume you have created a folder at D:\Project\GettingStartedOnMean. Now open a command prompt window and navigate to our working folder. Type following command to configure express-generator in local system.
npm install express-generator -g
npm stands for node package manager, if you are .net person it is similar to Nugets. npm gets installed with node.js setup. install parameter will tell npm to install package required for express-generator, our 3rd parameter. –g will tell npm to install this package globally, globally to your system.
Check the output of the above command. If you see error related to python files than please ignore it for now. We can still continue with this error. If you see error related to access privileges and you see difficulty getting this privilege than we can quickly fix this. Execute above command without –g, this will get all required files to your working folder under folder node_modules. Now for quick fix navigate your command window to node_modules\.bin and Type express [ApplicationName]. For sample application I am using ApplicationService.
express ApplicationService
If you were able to successfully install express-generator than you will have to execute this command at root of your working folder. Above command will create a folder with application name. If you have executed this command inside .bin folder under node_modules you will have to physically move this folder back to your root working folder and then delete node_modules folder created at the root working folder. We will no longer require node_modules folder at root working folder.
Next step is to get all the required packages for running our application. navigate your command prompt to ApplicationService folder and Type following command
Npm install will read package.json file which was created by express-generator for getting all the dependence and install it. To verify if you are on right track type
This will tell node and express to host your application. You can now access application UI at http://localhost:3000/. You can use ctrl + c to resume back to command window.
Ok now we are good with Express.js. It’s time to get mongodb. You should be able to get the installer from https://www.mongodb.org/downloads#production . Installer wizard should be able to guide you via installation process. After you have successfully installed mongodb, you should be able to access mongod and mongo exe via command prompt. If you are not able to access this exe directly from command prompt just verify your system environment variable path. It should have the path to mongodb bin folder. If you are still facing this issue than you will have to manually navigate your command window to bin folder. You can look at C:\Program Files\MongoDB\Server\3.0\bin based upon your processor architecture look into program files / program files (x86). In the command prompt type
mongod --dbpath D:\Project\GettingStartedOnMean\data
Mongod will host your database at port 27017 and database files will be available at D:\Project\GettingStartedOnMean\data. Do not forget to create data folder at the root of working folder. To keep it simple I have chosen to create folder inside working folder. You can change the location as per your convenience. For accessing the data from mongodb you can use Robomongo. It is a free tool for getting inside on mongodb data.
Next step is to get mongoose, object modeling tool for mongodb. We will be using mongoose for communicating between mongodb and express.js (node.js). Mongoose is also used for modeling your entity. For getting mongoose, navigate command prompt window to working folder/ application service. In my case path will be D:\Project\GettingStartedOnMean\ApplicationService\ and type following command.
npm install mongoose --save
First three parameter are already explained, fourth parameter will save the mongoose package information in package.json. In future if you are sharing your code with other team members he / she can use npm install to get the package locally. Now it’s time to write javascript code for exposing api data. Open your code in nodepad or any other editor which you are comfortable with. Microsoft have also release VSCode editor. You can download it from https://code.visualstudio.com/ . Ok now in your editor navigate to routes folder and add a new file paymentMode.js. Add following code for getting payment details from MongoDB server from pathDB database.
var express = require('express');<br />
var mongoose = require('mongoose');<br />
mongoose.connect('mongodb://localhost/pathDB');
var paymentModeSchema = mongoose.model('PaymentModes', {name: String, description: String});
var router = express.Router();
router.use(function(req, res, next) {<br />
res.header("Access-Control-Allow-Origin", "*");<br />
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");<br />
next();<br />
});
<br />
router.get('/getAll', function(req, res, next) {<br />
paymentModeSchema.find({},function(err, docs){<br />
res.json(docs);<br />
res.end();<br />
});<br />
});
module.exports = router;
Navigate to app.js in your text editor and add following lines of code at line 10 and 29. Below two lines will express to route api request to the code files which we have just added.
var payment = require('./routes/paymentMode');
app.use('/payment',payment);
Before running the app make sure you are running mongoDB database and you have data in mongoDB server under database pathDB. Type following after you navigate to ApplicationService folder inside command prompt.
Open any browser and enter http://localhost:3000/payment/getAll . You should be able to see data from your mongoDB database. If you are unable to see any response on your browser, check the command prompt for error.
Last step is to get angular.js to display data which is been exposed. Add a new folder at the root of working folder. I have named this folder Client but it is up to you to decide on folder structure. Since this a sample application I have added all my angular.js code in a single file. But it is not a good practice to do so. You can distribute your files as per the guideline shared by angular.js experts. Below is the sample code for reading API data and then displaying it’s output.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="paymentCtrl">
<ul>
<li ng-repeat="x in paymentOptions">
{{ x.name + ', ' + x.description}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('paymentCtrl', function($scope, $http) {
$http.get("http://localhost:3000/payment/getAll")
.then(function (response) {$scope.paymentOptions = response.data;});
});
</script>
</body>
</html>
You can dirrectly run the html in the browser to see the output. Make sure you are running ApplicationService and MongoDb instance. If you planning to run the attached sample application, please do not forget to run npm install inside ApplicationService folder before you run npm start
Points of Interest
In this article intention was not to cover best practices. I have written this article to present how simple and easy it is to write an application using Mean stack. Using a simple code editor and average system we should be able build and host an application. Since we are using JavaScript and Node.js application this can be deployed not only in Windows but also in Mac, Linux etc.
Reference
http://mean.io/
https://nodejs.org/en/
https://www.mongodb.org/
http://mongoosejs.com/