MEAN Stack: Developing an app with Angular 2+ and the Angular CLI

The MEAN stack comprises of advanced technologies used to develop both the server-side and the client-side of a web application in a JavaScript environment. The components of the MEAN stack include the MongoDB database, Express.js (a web framework), Angular (a front-end framework), and the Node.js runtime environment. Taking control of the MEAN stack and familiarizing different JavaScript technologies during the process will help you in becoming a full-stack JavaScript developer.
JavaScript’s sphere of influence has dramatically grown over the years and with that growth, there is an ongoing desire to keep up with the latest trends in programming. New technologies have emerged and existing technologies have been rewritten from the ground up (I am looking at you, Angular).
This tutorial intends to create the MEAN application from scratch and serve as an update to the original MEAN stack tutorial. If you are familiar with MEAN and want to get started with the coding, you can skip to the overview section.
Introduction to MEAN Stack
Node.js – Node.js is a server-side runtime environment built on top of Chrome’s V8 JavaScript engine. Node.js is based on an event-driven architecture that runs on a single thread and a non-blocking IO. These design choices allow you to build real-time web applications in JavaScript that scale well.
Express.js – Express is a minimalistic yet robust web application framework for Node.js. Express.js uses middleware functions to handle HTTP requests and then either return a response or pass on the parameters to another middleware. Application-level, Router-level, and Error-handling middlewares are available in Express.js.
MongoDB – MongoDB is a document-oriented database program where the documents are stored in a flexible JSON-like format. Being an NOSQL database program, MongoDB relieves you from the tabular jargon of the relational database.
Angular – Angular is an application framework developed by Google for building interactive Single Page Applications. Angular, originally AngularJS, was rewritten from scratch to shift to a Component based architecture from the age old MVC framework. Angular recommends the use of TypeScript which, in my opinion, is a good idea because it enhances the development work-flow.
Now that we are acquainted with the pieces of the MEAN puzzle, let’s see how we can fit them together, shall we?
Here is a high-level overview of our application.

We will be building an Awesome Bucket List Application from the ground up without using any boilerplate template. The front-end will include a form that accepts your bucket list items and a view that updates and renders the whole bucket list in real-time.
Any update to the view will be interpreted as an event and this will initiate an HTTP request. The server will process the request, update/fetch the MongoDB if necessary, and then return a JSON object. The front-end will use this to update our view. By the end of this tutorial, you should have a bucket list application that looks like this.

The entire code for the Bucket List application is available on GitHub.
First things first, you need to have Node.js and MongoDB installed to get started. If you are entirely new to Node, I would recommend reading the Beginner’s Guide to Node to get things rolling. Likewise, setting up MongoDB is easy and you can check out their documentation for installation instructions specific to your platform.
$ node -v
# v8.0.0

Start the mongo daemon service using the command.
sudo service mongod start

To install the latest version of Angular, I would recommend using Angular-CLI. It offers everything you need to build and deploy your angular application. If you are not familiar with the Angular CLI yet, make sure you check out The Ultimate Angular CLI Reference.
npm install -g @angular/cli

Create a new directory for our bucket list project. That’s where all your code will go, both the front end and the back end.
mkdir awesome-bucketlist
cd awesome-bucketlist

Creating the Backend Using Express.js and MongoDB
Express doesn’t impose any structural constraints on your web application. You can place the entire application code in a single file and get it to work, theoretically. However, your code base would be a complete mess. Instead, we are going to do this the MVC (Model, View, and Controller) way (minus the view part).
MVC is an architectural pattern that separates your models (the back-end) and views (the UI) from the controller (everything in between), hence MVC. Since Angular will take care of the front-end for us, we will have three directories, one for models and another one for controllers, and a public directory where we will place the compiled angular code.
In addition to this, we will create an app.js file that will serve as the entry point for running the Express server.

Although using a model and controller architecture to build something trivial like our bucket list application might seem essentially unnecessary, this will be helpful in building apps that are easier to maintain and refactor.
Initializing npm
We’re missing a package.json file for our back end. Type in npm init and, after you’ve answered the questions, you should have a package.json made for you.
We will declare our dependencies inside the package.json file. For this project we will need the following modules.

express: Express module for the web server
mongoose: A popular library for MongoDB
bodyparser: Parses the body of the incoming requests and makes it available under req.body
cors: CORS middleware enables cross-origin access control to our web server.

I’ve also added a start script so that we can start our server using npm start.
“name": "awesome-bucketlist",
"version": "1.0.0",
"description": "A simple bucketlist app using MEAN stack",
"main": "app.js",
"scripts": {
"start": "node app"

//The ~ is used to match the most recent minor version (without any breaking changes)

"dependencies": {
"express": "~4.15.3",
"mongoose": "~4.11.0",
"cors": "~2.8.3",
"body-parser": "~1.17.2"

"author": "",
"license": "ISC"

Now run npm install and that should take care of installing the dependencies.
Filling in app.js
First, we require all of the dependencies that we installed in the previous step.
// We will declare all our dependencies here
const express = require(‘express’);
const path = require(‘path’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);

//Initialize our app variable
const app = express();

//Declaring Port
const port = 3000;

As you can see, we’ve also initialized the app variable and declared the port number. The app object gets instantiated on the creation of the Express web server. We can now load middleware into our Express server by specifying them with app.use().
//Middleware for CORS

//Middleware for bodyparsing using both json and urlencoding

/*express.static is a built in middleware function to serve static files.
We are telling express server public folder is the place to look for the static files
app.use(express.static(path.join(__dirname, ‘public’)));

The app object can understand routes too.
app.get(‘/’, (req,res) => {
res.send("Invalid page");

Here, the get method invoked on the app corresponds to the GET HTTP method. It takes two parameters, the first being the path or route for which the middleware function should be applied.
The second is the actual middleware itself and it typically takes three arguments: The req argument corresponds to the HTTP Request; the res argument corresponds to the HTTP Response; and next is an optional callback argument that should be invoked if there are other subsequent middlewares that follow this one. We haven’t used next here since the res.send() ends the request-response cycle.
Add this line towards the end to make our app listen to the port that we had declared earlier.
//Listen to port 3000
app.listen(port, () => {
console.log(`Starting the server at port ${port}`);

npm start should get our basic server up and running.
By default, npm doesn’t monitor your files/directories for any changes and you have to manually restart the server every time you’ve updated your code. I recommend using nodemon to monitor your files and automatically restart the server when any changes are detected. If you don’t explicitly state which script to run, nodemon will run the file associated with the main property in your package.json.
npm install -g nodemon

We are nearly done with our app.js file. What’s left to do? We need to

Connect our server to the database.
Create a controller which we can then import to our app.js.

Setting up mongoose
Setting up and connecting a database is straightforward with MongoDB. First, create a config directory and a file named database.js to store our configuration data. Export the database URI using module.exports.
// 27017 is the default port number.
module.exports = {
database: ‘mongodb://localhost:27017/bucketlist’

And establish a connection with the database in app.js using mongoose.connect().
// Connect mongoose to our database
const config = require(‘./config/database’);

"But what about creating the bucket list database?", you may ask. The database will be created automatically when you insert a document into a new collection on that database.
Working on the controller and the model
Now let’s move on to create our bucket list controller. Create a bucketlist.jsfile inside the controller directory. We also need to route all the /bucketlist requests to our bucketlist controller (in app.js).
const bucketlist = require(‘./controllers/bucketlist’);

//Routing all HTTP requests to /bucketlist to bucketlist controller

Here is the final version of our app.js file.
Continue reading %MEAN Stack: Developing an app with Angular 2+ and the Angular CLI%


Node.js: A Next Gen Technology (Geek to Geek)


Node.js is a tool to run it as a web server to build a client server application
It uses to Google V8 engine to execute JavaScript code
Built upon event driven architecture
By default, the only single thread is responsible for handling the client request, but we can run multiple threads on the same machine to achieve scalability and fault tolerance.
In order to build an application, we need to use a third-party web framework like Express, Meteor, etc.

Application code gets compiled by V8 (JavaScript engine developed by Google to use in Chrome). The code communicates with low-level Node.js components via bindings. All the events written in the code are registered with Node.js. Once events are triggered, they are enqueued in the event queue according to the order that they are triggered. As long as there are events in the event queue, the event loop keeps picking them up, calling their callback functions, and sending them off to worker threads for processing. Once a callback function is executed, its callback is once again sent to the event queue, waiting to be picked up by the event loop again.
Components of Node.js
V8: V8 is Google’s open-source high-performance JavaScript engine, written in C++ and used in Chromium, Node.js, and multiple other embedding applications


A Practical Guide to Planning a MEAN Stack Application

A Practical Guide to Planning a MEAN Stack Application is an excerpt from Manning’s Getting MEAN with Mongo, Express, Angular, and Node, Second Edition. Getting MEAN, Second Edition is completely revised and updated to cover Angular 2, Node 6 and the latest mainstream release of JavaScript ES2015 (ES6). This Second Edition will walk you through how to develop web applications using this updated MEAN stack.
Planning a Real Application
For the purposes of this article, let’s imagine that we’re building a working application on the MEAN stack called Loc8r. Loc8r will list nearby places with WiFi where people can go and get some work done. It will also display facilities, opening times, a rating, and a location map for each place.
Planning the MEAN Stack Application at a High Level
The first step is to think about what screens we’ll need in our application. We’ll focus on the separate page views and the user journeys. We can do this at a high level, not concerning ourselves with the details of what’s on each page. It’s a good idea to sketch out this stage on a piece of paper or a whiteboard, as it helps to visualize the application in its entirety. It also helps with organizing the screens into collections and flows, serving as a good reference point when we build it. As there’s no data attached to the pages or application logic behind them, it’s easy to add and remove parts, change what’s displayed and where, and even change how many pages we want. The chances are that we won’t get it right the first time; the key is to start and iterate and improve until we’re happy with the separate pages and overall user flow.
Planning the Screens
Let’s think about Loc8r. As stated our aim is as follows:

Loc8r will list nearby places with WiFi where people can go and get some work done. It displays facilities, opening times, a rating, and a location map for each place. Visitors can to submit ratings and reviews.

From this we can get an idea about some of the screens we’re going to need:

A screen that lists nearby places
A screen that shows details about an individual place
A screen for adding a review about a place

We’ll probably also want to tell visitors what Loc8r is for and why it exists, and we should add another screen to the list:

A screen for “about us” information

Dividing the Screens into Collections
Next, we want to take the list of screens and collate them where they logically belong together. For example, the first three in the list are all dealing with locations. The About page doesn’t belong anywhere and it can go in a miscellaneous Others collection. Sketching this out brings us something like figure 1.

Figure 1: Collate the separate screens for our application into logical collections.
Having a quick sketch like this is the first stage in planning, and we need to go through this stage before we can start thinking about architecture. This stage gives us a chance to look at the basic pages, and to also think about the flow. Figure 1, for example, shows a basic user journey in the Locations collection, going from the List page, to a Details page, and then onto the form to add a review.
Continue reading %A Practical Guide to Planning a MEAN Stack Application%


Insights From an Open-Source Survey

A few weeks ago, we wrapped up a small survey on open-source software. The survey was focused on OSS and Node.js usage and turned up some interesting results.
I’ve collected some of the most unexpected and most interesting data from the survey and, with the help of the NodeSource team, pulled them into some pretty awesome charts to discuss the data and some of the ideas we can form from them.


How to Start Contributing to Node.js

Getting into an open-source project can seem a bit overwhelming. Whether you’re entirely new to open-source or not sure where your interests and skills could be helpful, it can be a hefty investment just to go and learn about a project before even thinking about contributing.
Node.js is a pretty massive project, with a lot of hidden areas that may not be immediately obvious to someone trying to get involved.


JavaScript Callback Hell: Solved

If you use Node.js, or some other similar technology based upon some react-to-events paradigm, you are almost certainly paying a TAX over your development, the so-called Callback Hell. Today we will look at how to solve Javascript Callback Hell. 
Specifically, it’s a TAX you pay every time you want to separate concerns and give some extra layer of indirection, such as when you apply some basic DDD layering. DAOs, Domain Services, Infrastructure Services, and stuff like that.


Node.js Security Release Summary

On July 11th, Michael Dawson announced expected updates to the Node.js 4, 6, 7 and 8 release lines. The possibility of a Denial of Service vulnerability in all release lines from 4.x to 8.x was shared at this time.
Additionally, two other security patches were included, one applicable to all Node.js releases (not just active release lines, but all versions) in a dependency of the project and another that’s exclusively applicable to the Node.js 4 release line.


Using MySQL with Node.js & the mysql JavaScript Client

NoSQL databases are all the rage these days and probably the preferred back-end for Node.js applications. But you shouldn’t architect your next project based on what’s hip and trendy, rather the type of database to be used should depend on the project’s requirements. If your project involves dynamic table creation, real time inserts etc. then NoSQL is the way to go, but on the other hand, if your project deals with complex queries and transactions, then a SQL database makes much more sense.
In this tutorial, we’ll have a look at getting started with the mysql module — a Node.js driver for MySQL, written in JavaScript. I’ll explain how to use the module to connect to a MySQL database, perform the usual CRUD operations, before examining stored procedures and escaping user input.

This popular tutorial was updated on 11.07.2017. Changes include updating to ES6 syntax, addressing the fact that the node-mysql module module was renamed, adding more beginner friendly instructions and adding a section on ORMs.

Quick Start: How to Use MySQL in Node
Maybe you’ve arrived here looking for a quick leg up. If you’re just after a way to get up and running with MySQL in Node in as little time as possible, we got you covered!
Here’s how to use MySQL in Node in 5 easy steps:

Create a new project: mkdir mysql-test && cd mysql-test
Create a package.json file: npm init –y
Install the mysql module: npm install mysql –save
Create an app.js file and copy in the snippet below.
Run the file: node app.js. Observe a “Connected!” message.


const mysql = require(‘mysql’);
const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘user’,
password: ‘password’,
database: ‘database name’
connection.connect((err) => {
if (err) throw err;

Installing the mysql Module
Now let’s take a closer look at each of those steps. First of all we’re using the command line to create a new directory and navigate to it. Then we’re creating a package.json file using the command npm init –y. The -y flag means that npm will use only defaults and not prompt you for any options.
This step also assumes that you have Node and npm installed on your system. If this is not the case, then check out this SitePoint article to find out how to do that: Install Multiple Versions of Node.js using nvm.
After that, we’re installing the mysql module from npm and saving it as a project dependency. Project dependencies (as opposed to dev-dependencies) are those packages required for the application to run. You can read more about the differences between the two here.
mkdir mysql-test
cd mysql-test
npm install mysql -y

If you need further help using npm, then be sure to check out this guide, or ask in our forums.
Getting Started
Before we get on to connecting to a database, it’s important that you have MySQL installed and configured on your machine. If this is not the case, please consult the installation instructions on their home page.
The next thing we need to do is to create a database and a database table to work with. You can do this using a
graphical interface, such as phpMyAdmin, or using the command line. For this article I’ll be using a database called sitepoint and a table called employees. Here’s a dump of the database, so that you can get up and running quickly, if you wish to follow along:
CREATE TABLE employees (
name varchar(50),
location varchar(50),

INSERT INTO employees (id, name, location) VALUES
(1, ‘Jasmine’, ‘Australia’),
(2, ‘Jay’, ‘India’),
(3, ‘Jim’, ‘Germany’),
(4, ‘Lesley’, ‘Scotland’);

Connecting to the Database
Now, let’s create a file called app.js in our mysql-test directory and see how to connect to MySQL from Node.js.
Continue reading %Using MySQL with Node.js & the mysql JavaScript Client%


Real-World Angular Series, Part 4a: Access Management, Admin, and Detail Pages

The third part of this tutorial (Part 3a and Part 3b) covered fetching, filtering, and displaying API data.
The fourth installment in the series covers access management with Angular, displaying admin data, and setting up detail pages with tabs.