Getting MEAN – Introducing full-stack development

The MEAN stack is a pure JavaScript stack comprised of four main technologies, with a cast of supporting technologies:

  • MongoDB — the database
  • Express — the web framework
  • Angular — the front-end framework
  • Node.js — the web server

Why the MEAN stack specifically?

The MEAN stack pulls together some of the "best-of-breed" modern web technologies into a very powerful and flexible stack. One of the great things about the MEAN stack is that it not only uses JavaScript in the browser, it uses JavaScript throughout. Using the MEAN stack, you can code both the front end and back end in the same language.

The principle technology allowing the this to happen is Node.js, bringing JavaScript to the back end.

Introducing Node.js The web server/platform

JavaScript: The single language through the stack

With the release of Node.js you can leverage what you already know and put it to use on the server. One of the hardest parts of learning a new technology like this is learning the language, but if you already know some JavaScript then you're one step ahead!

Fast, efficient, and scalable

Another reason for the popularity of Node.js is ,when coded correctly, it's extremely fast and makes very efficient use of system resources. This enables a Node.js application to serve more users on fewer server resources then most of the other mainstream server technologies. Business owners also like the idea of Node.js because it can reduce their running costs, even at a large scale.

Node.js is light on system resources because it's single-threaded, whereas traditional web server are multithreaded.

Traditional multithreaded web server

This approach works perfectly well as long as you have enough tellers to service the customers.

This is one of the reasons why web servers are often overpowered and have so much RAM, even though they don't need it 90% of the time.

fig_1-3

A single-threaded web server

A Node.js server is single-threaded and works differently than the multithreaded server. Rather than giving each visitor a unique thread and a separate silo of resources, every visitor joins the same thread. A visitor and thread interact only when needed, when the visitor is requesting something or thread is responding to a request.

fig_1-4

Blocking versus nonblocking code

With the single-threaded model, it's important to remember that all of your users use the same central process. To keep the flow smooth, you need to make sure that nothing in your code causes a delay, blocking another operation.

Similarly, if your central process is responsible for reading each static file (such as CSS, JavaScript, or images) it won't be able to process any other request, the blocking the flow. Another common task that's potentially blocking is interacting with a database. If your process is going to the database each time it's asked, be it searching for data or saving data, it won't be able to do anything else.

So for the single-threaded approach to work, you must make sure your code is nonblocking. The way to achieve this is to make any blocking operations run asynchronously, preventing them from blocking the flow of your main process.


Introducing Express: The framework

Express is the E in MEAN. Because Node.js is a platform, it doesn't prescribe how it should be set up or used. This is one of its great strengths. But when creating websites and web applications, there are quite a few common tasks that need doing every time. Express is a web application framework for Node.js that has been designed to do this in a well-tested and repeatable way.

Easing your server setup

As already noted, Node.js is a platform, not a server. This allows you to get creative with your server setup and do things that other web servers can't do. It also makes it harder to get a basic website up and running.

Express abstracts away this difficult by setting up a web server to listen to incoming requests and return relevant responses. In addition, it also defines a directory structure. One of these folders is set up to serve static files in a nonblocking way; the last thing you want is for your application to have to wait when somebody else requests a CSS file! You could configure

Routing URLs to responses

One of the great features of Express is that it provides a really simple interface for directing an incoming URL to a certain piece of code. Whether this is going to serve a static HTML page, read from a database, or write to a database doesn't really matter. The interface is simple and consistent.

What Express has done is abstract away some of the complexity of doing this in native Node.js, to make code quicker to write and easier to maintain.

Views: HTML responses

It's likely that you'll want to respond to many of the requests to your application by sending some HTML to the browser. By now it will come as no surprise to you that Express makes this easier than it is in native Node.js.

Express provides support for many different templating engines that make it easier to build HTML pages in an intelligent way, using reusable components as well as data from your application. Express compiles these together and serves them to the browser as HTML.

Remembering visitors with session support

Being single-threaded, Node.js doesn't remember a visitor from one request to the next. It doesn't have a silo of RAM set aside just for you; it sees only a series of HTTP requests. HTTP is a stateless protocol, so there's no concept of storing a session state. As it stands, this makes it difficult to create a personalized experience in Node.js or have a secure area where a user has to log in: it's not much use if the site forgets who you are on every page. You can do it, of course, but you have to code it yourself.

Express comes with the ability to use sessions so that you can identify individual visitors through multiple requests and pages.

Sitting on top of Node.js, Express gives you a great helping and a sound starting point for building web applications. It abstracts away many complexities and repeatable tasks that most o us don't need — or want — to worry about. We just want to build web applications.


Introducing MongoDB: The database

The ability to store and use data is vital for most applications. In the MEAN stack, the database of choice is MongoDB, the M in MEAN. MongoDB fits into the stack incredibly well. Like Node.js, it's renowned for being fast and scalable.

Relational versus document databases

Mongo DB is a document database. The concept of rows still exists but columns are removed from the picture. Rather than a column defining what should be in the row, each row is a document, and this document both defines and holds the data itself.

This less-structured approach means that a collection of documents could have a wide variety of data inside.

MongoDB documents: JavaScript data store

MongoDB stores documents as BSON, which is binary JSON (JavaScript serialized Object Notation). In short, JSON is a JavaScript way of holding data, hence why MongoDB fits so well into the JavaScript-centric MEAN stack!

More than just a document database

MongoDB sets itself apart from many other document databases with its support for secondary indexing and rich queries. This means that you can create indexes on more than just the unique identifier field, and querying indexed fields is much faster. You can also create some fairly complex queries against a MongoDB database — not to the level of huge SQL commands with coins all over the place, but powerful enough for most use cases.

What is MongoDB not good for?

Mongo DB isn't a transactional database and shouldn't be used as such. A transactional database can take several separate operations as one transaction. If any one of the operations in a transaction should fail, the entire transaction fails and none of the operations complete.

Mongoose for data modeling and more

MongoDB's flexibility about what it stores in documents is a great thing for the database. But most applications need some structure to their data. Note that it's the application that needs the structure, not the database. So where does it make most sense to define the structure of your application data? In the application itself!

To this end, the company behind MongoDB created Mongoose. In their own words, Mongoose provides "elegant MongoDB object modeling for Node.js".

What is data modeling?

Data modeling, in the context of Mongoose and MongoDB, is defining what data can be in a document, and what data must be in a document. This information is defined in a schema, which is used as the basis for the data model.

What else does mongoose offer?

As well as modeling data, Mongoose adds an entire layer of features on top of MongoDB that are useful when building web applications. Mongoose makes it easier to manage the connections your MongoDB database, and to save and read data. We'll use all of this later. We'll also discuss how Mongoose enables you to add data validation at the scheme level, making sure that you allow only valid data to be saved in the database.

MongoDB is great choice of database for most web applications because it provides a balance between the speed of pure. Document databases and the power of relational databases. That the data is effectively stored in JSON makes it the perfect data store for the MEAN stack.


Introducing Angular: The front-end framework

Angular is the A in MEAN. In simple terms, Angular is a JavaScript framework for creating the interface for your website or application. In this book, you'll be working with Angular 2.

You could use Node.js, Express, and MongoDB to build a fully functioning data-driven web application. But you can put some icing on the cake by adding Angular to the stack.

The traditional way of doing things is to have all data processing and application logic on the server, which then passes HTML to the browser. Angular enables yo auto move some or all of this processing and logic to the browser, often leaving the server just passing data from the database.

jQuery versus Angular

If you're familiar with jQuery, you might be wondering if Angular works the same way. The short answer is no, not really. Jquery is generally added to a page to provide interactivity, after the HMTL has been sent to the browser and the Document Object Model (DOM) has completely loaded. Angular comes in a step earlier puts the HTML together based on the data provided.

Aslo jQuery is a library, and as such has a collection of features that you can use as you wish. Angular is what is known as an opinionated framework. This means the it forces its opinion on you as to how it needs to be used.

As mentioned, Angular haps put the HTML together based on the data provided ,but it does more than this. It also immediately updates the HTML if the data changes, and can also update the data if the HMTL changes. This is known as two-way data binding.

Two-way data binding: Working with data in a page

To understand two-way data binding let's start with a look at the traditional approach of one-way data binding. One-way data binding is what you're aiming for when looking at using Node.js, Express, and MongoDB. Node.js gets the data from MongoDB, and Express then uses a template to compile this data into HTML that's then delivered to the server. This process is illustrated in figure 1.5.

fig_1-5

This one-way model is the basis for a lot of database-driven websites. In this model, most of the hard work is done on the server, leaving the browser to just render HTML and run any JavaScript interactivity.

Two-way data binding is different.

  • First, the template and data are sent independently to the browser. The browser itself compiles the template into the view and the data into a model.
  • The real difference is that the view is "live." The view is bound to the model, so if the model changes the view changes instantly. On top of this, if the view changes the model also changes. Two-way binding is illustrated in figure 1.6.

fig_1-6

Because your data store is likely to be exposed via an API and not tightly coupled to the application, there's typically some processing involved before adding it to the model. You want to make sure that you're binding the correct, relevant data to the view.

Using Angular to load new pages

Something that Angular has been specifically designed for is single-page application (SPA) functionality. In real terms, an SPA runs everything inside the browser and never does a full page reload. What this means is that all applications logic, data processing, user flow, and template delivery can be managed in the browser.

Are there any downsides?

Despite its many benefits, Angular isn't appropriate for every website. Front-end libraries like jQuery are best used for progressive enhancement. The idea is the your site will function perfectly well without Javascript, and the JavaScript you use makes the experience better. That isn't the case with Angular, or indeed any other SPA framework. Angular uses JavaScript to build the rendered HTML from templates and data, so if you browser doesn't support JavaScript, or if there's bug in the code, then the site won't run.

One thing you can do is use Angular for some things and not others. There's nothing wrong with using Angular selectively in your project. For example, you might have a data-rich interactive application or section of your site that's ideal for building in Angular. You might also have a blog or some marketing pages around you application. These don't need to be built in Angular, and arguably would be better served from the server in the traditional way. So part of your site is served by Node.js, Express, and MongoDB, and another part also has Angular doing its thing.

Supporting cast

The MEAN stack gives you everything you need for creating data-rich interactive web applications, but you may wheat to use a few extra technologies to help you on the way. You an use Twitter Bootstrap to help create a good user interface, Git to help manage your code, and Heroku to help hosting the application on a live URL.

Twitter Bootstrap for user interface

Bootstrap is a front-end framework that provides a wealth of help for creating a great user interface. Among its features, Bootstrap provides a responsive grid system, default styles for many interface components, and the ability to change the visual appearance with themes.

Responsive grid layout

In a responsive layout, your serve up a single HTML page that arranges itself differently on different devices. This is done through detecting the screen resolution rather than trying to sniff out the actual device.

CSS classes and HTML components

Bootstrap comes with a set of predefined CSS classes that can create useful visual components. These include things like page headers, flash-message containers, labels and badges, stylized lists … the list goes on! They've thought of a lot, and it really helps you quickly build an application without having to spend too much time on the HTML layout and CSS styling.

Adding themes for a different feel

Bootstrap has a default look and feel that provides a really neat baseline. This is so commonly used your site could end up looking like anybody else's. Fortunately, it's possible to download themes for Bootstrap to give your application a different twist. Downloading a theme is often as a simple as replacing the Bootstrap CSS file with a new one.

Hosting with Heroku

Hosting Node.js applications can be complicated, but it doesn't have to be. Many traditional shared hosting providers haven't kept up with the interest in Node.js. Some will install it for you so that you can run applications, but the servers are generally not set up to meet the unique needs of Node.js. To run a Node.js application successfully you need. Either a server that has been configured with that in mind, or you can use a Pass provider that's aimed specifically at hosting Node.js.

Heroku is one of the leading hosts for node.js applications, and it has an excellent free tier that we'll be making use of.

Applications on Heroku are essentially Git repositories, making the publishing process incredibly simple. After everything is set up you can publish your application to a live environment using a single command:

$ git push heroku master

Putting it together with a practical example

As already mentioned a few times, throughout the course of this book we'll build a toking application on the MEAN stack. This will give you a good grounding in each of the technologies, as well as showing how they all fit together.

How the MEAN stack components work together

MongoDB stores data in binary JSON, which through Mongoose is exposed as JSON. The Express framework sits on top of Node.js, where the code is all written in JavaScript. In the front end is Angular, which again is JavaScript.

fig_1-8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s