Tải bản đầy đủ (.pdf) (453 trang)

Web development with MongoDB and node third edition build fast web applications for handling any kind of data

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.96 MB, 453 trang )


Web Development with MongoDB and Node


Third Edition

Build fast web applications for handling any kind of data


Bruno Joseph D'mello

Mithun Satheesh

Jason Krol

BIRMINGHAM - MUMBAI


Web Development with MongoDB
and Node


Third Edition
Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, without the
prior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the
accuracy of the information presented. However, the information contained in


this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing, and its dealers and distributors will be held
liable for any damages caused or alleged to be caused directly or indirectly by
this book.
Packt Publishing has endeavored to provide trademark information about all
of the companies and products mentioned in this book by the appropriate use
of capitals. However, Packt Publishing cannot guarantee the accuracy of this
information.

First published: September 2014
Second edition: October 2015
Third edition: September 2017


Production reference: 1260917

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78839-508-3

www.packtpub.com


Credits

Authors
Copy Editor

Bruno Joseph D'mello
Charlotte Carneiro
Mithun Satheesh
Jason Krol

Reviewer

Project Coordinator

Alex Bachuk

Sheejal Shah

Commissioning Editor

Proofreader


Smith Thakkar

Safis Editing

Acquisition Editor

Indexer

Reshma Raman

Rekha Nair


Content Development Editor

Graphics

Jason Pereira

Jason Monteiro

Technical Editor

Production Coordinator

Surabhi Kulkarni

Melwyn D'sa



About the Authors
Bruno Joseph D'mello works at Yapsody as a software engineer. He has
possesses almost 5 years of experience in web application development,
serving industries such as entertainment, social media, enterprise, and IT
services. He is a JavaScript enthusiast and dedicatedly worked on it for the
past 4 years. Apart from rare commits, he believes in contributing to open
source by actually mentoring new technologies to beginners and involving
them in open source communities. Bruno follows Kaizen and enjoys the
freedom of architecting new things on the web. He also contributed his
knowledge by authoring books such as Web Development in Node.js and
Mongodb second edition, What You Need to Know About Node.js (Free
ebook), and by being a reviewer.

You can connect with Bruno at:
"Thanks to my family for patience and encouragement, especially Erina..."

Mithun Satheesh is an open source enthusiast and a web developer who
resides in India. He has more than 5 years of experience in web development
and specializes in JavaScript, Ruby, PHP, and other frontend engineering
technologies. He is the author of a couple of libraries on Node.js, which are
available open source via npm. One of these, called node-rules, is a forwardchaining rule engine implementation written initially to handle transaction
risks on bookmyshow, one of his former employers. Node-rules have a
considerable user following both on npm and GitHub.
Apart from this, he has also served as an individual contributor in many open


source projects on GitHub.
He is a regular on programming sites, such as Stack Overflow, and loves
contributing to the open source world. Apart from programming, he is also
interested in experimenting with various cloud platform solutions. He has a
number of applications listed in the developer spotlight of Platform-as-aService providers, such as RedHat's OpenShift.
Jason Krol is a passionate web developer with over 15 years of professional
experience creating highly interactive web applications using the latest in
both client and server technologies.
Over the past few years, Jason has been focusing on developing Single-Page
Applications using JavaScript in the full stack with Node.js, MongoDB, and
Backbone.js. After co-owning and running a successful web development
agency for a number of years, Jason recently joined AWeber
Communications, an e-mail marketing service provider in the suburbs of
Philadelphia.


About the Reviewer

Alex Bachuk is a web developer with over 9 years of experience and
specializes in custom JavaScript web applications. Currently, Alex leads the
Rental Cars Web UX team at priceline.com and runs JavaScript and React
workshops in NYC area along with the EcmaStack.com team.
Alex organizes and talks at JavaScript, Meteor.js, and GraphQL meetups in
the New York City area. In his free time, he likes to spend time with his
family and also travel the world.


www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub
.com.
Did you know that Packt offers eBook versions of every book published, with
PDF and ePub files available? You can upgrade to the eBook version at www.P
acktPub.com and as a print book customer, you are entitled to a discount on the
eBook copy. Get in touch with us at for more details.
At www.PacktPub.com, you can also read a collection of free technical articles,
sign up for a range of free newsletters and receive exclusive discounts and
offers on Packt books and eBooks.

/>
Get the most in-demand software skills with Mapt. Mapt gives you full
access to all Packt books and video courses, as well as industry-leading tools
to help you plan your personal development and advance your career.


Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser



Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our
editorial process. To help us improve, please leave us an honest review on
this book's Amazon page at />If you'd like to join our team of regular reviewers, you can e-mail us at
We award our regular reviewers with free eBooks
and videos in exchange for their valuable feedback. Help us be relentless in
improving our products!


Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions

1.

Welcome to JavaScript in the Full Stack
A short introduction to Node.js
The advantage that the V8 engine brings in
Node.js is single-threaded!

Non-blocking asynchronous execution
npm - the Node Package Manager
Sharing and reusing JavaScript
Not just for building web servers!
Real-time web application with Socket.io
Networking and file IO
Microservices
Internet of things (IoT)
A simple server with Node.js
When to use Node.js
The NoSQL movement
A short introduction to MongoDB
JSON-friendly database
Schema-less design
Various performance facets
Node.js and MongoDB in the wild
What to expect from this book
Summary

2.

Getting Up and Running
Installing Node.js


Mac OS X
Windows
Linux
Testing that Node.js is installed properly
Online documentation

Installing MongoDB
Mac OS X installation instructions
Windows 7/Windows 8 installation instructions
Linux installation instructions
Confirming successful MongoDB installation
Bookmarking the online documentation
Writing your first app
Creating the sample application
Getting the dependent modules in place
Adding the application code
Understanding the code
Launching the sample app
Checking the actual database
Summary

3.

Node and MongoDB Basics
A JavaScript primer
Introducing es6
Syntax basics
Understanding the scope of variables
Data types
Operators and flows
Understanding objects
Understanding arrays
Understanding functions
Anonymous functions and callbacks
JSON
The basics of Node.js

Node.js architecture
Event-driven
Asynchronous execution
The module system
The Node.js core


HTTP
Net
Streams
Installing modules using npm
The basics of MongoDB
The Mongo shell
Inserting data
Querying
Updating data
Deleting data
Additional resources
Summary

4.

Introducing Express
Web application frameworks
What is Express.js?
Building a complete web application
Designing the web application
Organizing the files
Creating the application's entry point
Booting up the application

Middlewares
Creating custom middleware
Order of middlewares
The configure module
Activating the configure module
Routers and controllers
Handlebars as View engines
Summary

5.

Templating with Handlebars
Templating engines
Server-side and client-side templating
Client-side templating
Server-side templating
The basics of Handlebars
Binding an object to the template
Embedding presentation logic
Views


Layouts
Partial views
Handlebars helpers
Global helpers
View-specific helpers
Rendering the views
Summary


6.

Controllers and View Models
Controllers
View models
Updating the home controller
Updating the image controller
Displaying an image
Uploading an image
Helpers for reusable code
The sidebar module
The stats module
The images module
The comments module
Testing the sidebar implementation
Iterating on the UI
Summary

7.

Persisting Data with MongoDB
Using MongoDB with Node.js
Connecting to MongoDB
Inserting a document
Retrieving a document
Introducing Mongoose
Schemas
Models
Built-in validation
Static methods

Virtual properties
Context of method (this)
Connecting with Mongoose
Defining the schemas and models
The models index file
Adding CRUD to the controllers


The home controller
The image controller
Index - retrieving an image model
Create - inserting an image model
Testing everything out so far
The like button and updating an image model
Comment - inserting a comment model
Wrapping it up
Helpers
Introducing the async module
The comments helper
The sidebar helper
Troubleshooting
The stats helper
The popular images helper
Iterating by adding an image removal capability
Adding a route
Adding a controller handler
Updating the Handlebars image page template
Updating jQuery
Refactoring and improvements
Summary


8.

Creating a RESTful API
What is an API?
What is a RESTful API?
Introducing Postman REST Client
Installation instructions
A quick tour of Postman REST Client
Using the JSONView Chrome extension
Creating a basic API server
Creating sample JSON data
Responding to GET requests
Receiving data - POST and PUT requests
Removing data - DELETE
Consuming external APIs from Node.js
Consuming an API endpoint using request
Summary


9.

Testing Your Code
The tools of the trade
Running tests with the Mocha framework
Asserting tests with Chai.js
Getting started with Chai
Spies and stubs with Sinon.js
Stubbing node modules with Proxyquire
Writing and running your first test

Writing a test helper
Testing the application
Testing the routes
Testing the server
Testing a model
Testing a controller
Spy and stub everything!
Automating everything
Summary

10.

Deploying with Cloud-Based Services
Cloud versus traditional hosting
Infrastructure as a Service versus Platform as a Service
An introduction to Git
Deploying your application
Nodejitsu
Heroku
Amazon Web Services
Creating a MongoLab account and database
Create and configure the AWS environment
Microsoft Azure
Digital Ocean
Summary

11.

Popular Node.js Web Frameworks
Koa

Meteor
Sails
Flatiron
total.js
LoopBack


Hapi
Kick starting Hapi.js
Scaffolding the Hapi app
Setting up a server
Creating APIs
Creating a configuration-based architecture
Summary

12.

Single Page Applications with Popular Frontend Frameworks
Why use a frontend framework?
What is a single page application?
The TodoMVC project
Backbone.js
Ember.js
React.js
Angular
Scaffolding the Angular app
Understanding TypeScript and es6
Modules and components
Angular data flow architecture
Services

Forms
Component communication
Frontend development tools
Automated build task managers
Dependency management
Modularity
HTML template-rendering engines
CSS transpiling
Testing and test-driven development
PhantomJS headless browser
Summary


Preface
With the advent of ECMAscript 6, the usability of Node.JS has a great scope
for future and has already been implemented today. The need of learning es6
syntactic sugar and inclusion of most of the cross-technology features
inspires different technological communities to learn JavaScript.
The high performance and scalability of Node.js and open source NoSQL
database solution called MongoDB cater to building fast, scalable network
applications easily. This combination makes managing any form of data easy
and ensures its delivery speed.
This book aims to provide different facets of web application development
with Node.JS and MongoDB that is used to build an isomorphic server-side
rendering web application. This books also guides us in creating a
configurable Node.JS server using hapi.js and learning to develop a singlepage frontend app using Angular 4.
This book will begin by introducing you to the groundwork needed to set up
the development environment and a comparative study on how the new
ECMAscript is different from the traditional JavaScript. Once the base is
ready, we will quickly run through the steps necessary to get the main

application server up and running and to learn the Node.JS core.
Further, we will move toward advanced coding techniques using controllers
and ViewModels to generate reusable code that reduces development time.
The development ends with learning proper testing concepts and how to
automate them for reusability and maintainability.
By the end of the book, you will be connected with JavaScript ecosystem and
will go through the trendy JavaScript frontend and backend frameworks.


What this book covers
Welcome to JavaScript in the Full stack, provides an introduction on
Node.js and MongoDB. In addition to this, it will explain the overall
architecture of the application you will build using this book.
Chapter 1,

Getting Up and Running, explains how to set up the development
environments for Node.js and MongoDB. You will also verify that
everything is set up properly by writing a sample app and running it.
Chapter 2,

Node and MongoDB Basics, is about learning JavaScript at base.
Further, going through need to know concepts of NodeJS and basic CRUD
operations on MongoDB.
Chapter 3,

Introducing Express, introduces you to the Express framework and
its various components. It also walks you through organizing the basic
application that you are building with this framework. It will also give you a
detailed overview of the MVC components of Express.
Chapter 4,


Templating with Handlebars, introduces you to the concept of using
a templating engine and handlebars. Also, it shows you how to use
handlebars in your application as a templating engine.
Chapter 5,

Controllers and View Models, shows you how to organize the code
for the sample application you build into the controllers and view of the
Express framework. It will introduce you to the MVS concepts indirectly via
introducing the need of separating the code into various modules and utilizing
the Express framework.
Chapter 6,

Persisting Data with MongoDB, shows you how to connect to the
MongoDB server from the Node.js application you are building. It will also
introduce you to the concept of ODM, the most popular one being Mongoose.
Chapter 7,

Chapter 8,

Creating a RESTful API, introduces you to RESTful APIs. Also, it


×