Click here to Skip to main content
15,036,737 members
Articles / Internet of Things / Raspberry-Pi
Article
Posted 23 Dec 2015

Stats

28.4K views
125 downloads
9 bookmarked

Getting Started with Mean Stack

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
23 Dec 2015CPOL8 min read
Writing your first app using Mean Stack (M = MongoDB, E = Express.JS, A = Angular.JS and N = Node.js)

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 

C++
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.

C++
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.

C++
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

C++
npm install

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 

C++
npm start

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 

C++
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. 

C++
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'); //mongodb Server and Database information. pathDB is the name of the database

//Your schema defination. PaymentModes is the table / collection name inside PathDb database<br />
var paymentModeSchema = mongoose.model('PaymentModes', {name: String, description: String});

//router is used to expose your api to external world<br />
var router = express.Router();

//This will allow cross browser access to our API<br />
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 />
});

/* GET home page. */<br />
router.get('/getAll', function(req, res, next) {<br />
    //paymentModeSchema will use Find api and return the data which fits its criteria. I have left the criteria<br />
    //blank for getting all the records from the table.<br />
    paymentModeSchema.find({},function(err, docs){<br />
        //response is returned JSON format<br />
        res.json(docs);<br />
        // we need to end to response.<br />
        res.end();<br />
    });<br />
});

//expose your api to external world<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.

//GettingStartedOnMean : Step 1 : require added for getting payment information<br />
var payment = require('./routes/paymentMode');

//GettingStartedOnMean : Step 2 :  route added for getting payment information<br />
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. 

C++
npm start

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. 

HTML
<!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/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ashwin. Shetty
Architect
India India
I have 17 years of experience working in Microsoft Technology & Open source. Now a days I enjoy playing with Nodejs, Angular, docker, Gcloud & Kubernetes. My complete profile is available at https://in.linkedin.com/in/ashwinshetty and you can mail me at ashwin@shettygroup.com

Comments and Discussions

 
QuestionEasy to Understand steps Pin
PramodPetkar23-Dec-15 6:19
MemberPramodPetkar23-Dec-15 6:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.