Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Web Development with MongoDB and Node.js
Web Development with MongoDB and Node.js

Web Development with MongoDB and Node.js: Build an interactive and full-featured web application from scratch using Node.js and MongoDB

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Web Development with MongoDB and Node.js

Chapter 1. Welcome to JavaScript in the Full Stack

What an exciting time to be a JavaScript developer! What was once only considered a language to add enhancements and widgets to a webpage has since evolved into its own full-fledged ecosystem. I believe Atwood's law says it best— any application that can be written in JavaScript, will eventually be written in JavaScript. While this quote dates back to 2007, it's never been more true than today. Not only can you use JavaScript to develop a complete single-page web application such as Gmail, but you will also see how we can achieve the following projects with JavaScript throughout the remaining part of the book:

  • How to completely power the backend using Node.js and Express.js
  • How to persist data with a powerful database like MongoDB
  • How to write dynamic HTML pages using Handlebars.js
  • How to deploy your entire project to the cloud using services like Heroku and AWS

With the introduction of Node.js, JavaScript has officially gone in a direction that was never even possible before. Now, you can use JavaScript on the server, and you can also use it to develop full-scale enterprise-level applications. When you combine this with the power of MongoDB and its JSON-powered data, you can work with JavaScript in every layer of your application.

One of the great advantages of developing with JavaScript in the "full stack" of a web application is that you are using a consistent language and syntax. Frameworks and libraries are no longer exclusive only to the frontend or backend but can be integrated into other layers of the application as well.

Underscore.js is an extremely popular JavaScript library to work with collections that is used equally on the backend with Node.js as much as on the frontend directly within the browser.

Welcome to JavaScript in the Full Stack

JavaScript in the full stack of a web application

Node.js changed JavaScript forever

Back in 2009, Ryan Dahl gave a presentation at JSConf that changed JavaScript forever. During his presentation, he introduced Node.js to the JavaScript community, and after a roughly 45-minute talk, he concluded it, receiving a standing ovation from the audience in the process. He was inspired to write Node.js after he saw a simple file upload progress bar on Flickr, the image-sharing site. Realizing that the site was going about the whole process the wrong way, he decided that there had to be a better solution.

As stated on the Node.js homepage, the goal of Node is to provide an easy way to build scalable network programs. It achieves this by providing an event-driven, nonblocking IO model that is extremely lightweight. Compared to traditional web-serving technologies that require a new CPU thread for every connection to the server that would eventually max out the systems resources, Node instead uses a single thread but doesn't block the I/O of the CPU. Thus, this allows Node to support tens of thousands of concurrent connections. It's for this very reason that Node is so popular with high-traffic web applications.

To see an example of just how lightweight Node can be, let's take a look at some sample code that starts up an HTTP server and sends Hello World to a browser:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080');

A few basic lines of code are all it takes to write a complete Node application. Running it with a simple node app.js command will launch an HTTP server that is listening on port 8080. Point any browser to http://localhost:8080, and you will see the simple output Hello World on your screen! While this sample app doesn't actually do anything useful, it should give you a glimpse of the kind of power you will have while writing web applications using Node.js.

At its core, Node is very low-level. It consists of a small set of modules that do very specific things and do them very well. These modules include tools to work with the file system, networking with TCP and HTTP, security, and streams.

Asynchronous callbacks

One of the most powerful features of Node is that it is event-driven and asynchronous. Code gets executed via callback functions whenever an event is broadcast. Simply put, you assign a callback function to an event, and when Node determines that the event has been fired, it will execute your callback function at that moment. No other code will get blocked waiting for an event to occur. Consider the following example to see asynchronous callbacks in action:

console.log('One');
console.log('Two');
setTimeout(function() {
    console.log('Three');
}, 2000);
console.log('Four');
console.log('Five');

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

In a typical synchronous programming language, executing the preceding code will yield the following output:

One
Two
... (2 second delay) ...
Three
Four
Five

However, in JavaScript and Node, the following output is seen:

One
Two
Four
Five
... (approx. 2 second delay) ...
Three

The function that actually logs Three is known as a callback to the setTimeout function.

Node Package Manager

Writing applications with Node is really enjoyable when you realize the sheer wealth of information and tools at your disposal! Using Node's built-in package manager npm, you can find literally tens of thousands of modules that can be installed and used within your application with just a few keystrokes! You can view the library of available modules by visiting http://npmjs.org. Downloading and installing any module within your application is as simple as executing the npm install package command. Have you written a module that you want to share with the world? Package it up using npm, and upload it to the public npmjs.org registry just as easily! Not sure how a module works that you downloaded and installed? The source code is right there in your projects' node_modules/ folder waiting to be explored!

Networking and file IO

In addition to the powerful nonblocking asynchronous nature of Node, it also has very robust networking and filesystem tools available via its core modules. With Node's networking modules, you can create server and client applications that accept network connections and communicate via streams and pipes.

Not just on the web

Node isn't just for web development! It can be a powerful solution to create command-line tools as well as full-featured locally run applications that have nothing to do with the Web or a browser. Grunt.js is a great example of a Node-powered command-line tool that many web developers use daily to automate everyday tasks such as build processes, compiling CoffeeScript, launching Node servers, running tests, and more.

In addition to command-line tools, Node has recently become increasingly popular among the hardware crowd with the Nodebots movement. Johnny-Five and Cylon.js are two popular Node libraries that exist to provide a framework to work with robotics.

Real-time web with Socket.io

Node achieves real-time communication with Socket.io. Using Socket.io, you can create features such as instant collaboration, which is similar to multiuser editing in Google Docs. What was once achieved using cumbersome (and not real-time) long polling can now be achieved using WebSockets. While WebSockets is a feature that is only supported in modern browsers, Socket.io also features seamless fallback implementations for legacy browsers.

Using this lightweight core, everything else is left to the developer—but don't let that scare you. The beauty of working with Node is that there is a thriving community developing and releasing modules every day via npm. As of this writing, npm has over 61,000 packages available! Throughout this book, we will use some of the most popular packages that help make writing web applications fun and easy!

The NoSQL movement

The term NoSQL has come to mean any kind of database that doesn't adhere to the strict structures of a typical relational database such as Microsoft SQL, MySQL, PostgreSQL, and so on. With a relational database, you are required to define ahead of time the exact structure of your schema. This means that you must have defined the exact number of columns, length, and datatype for every field in a table, and that each field must always match that exact set of criteria.

With a NoSQL database server such as MongoDB, records are stored as JSON-like documents. A typical document (record) in a MongoDB collection (table) might look like the following code:

$ mongo
> db.contacts.find({email: 'jason@kroltech.com'}).pretty()

{
    "email" : "jason@kroltech.com",
    "phone" : "123-456-7890",
    "gravatar" : "751e957d48e31841ff15d8fa0f1b0acf",
    "_id" : ObjectId("52fad824392f58ac2452c992"),
    "name" : {
        "first" : "Jason",
        "last" : "Krol"
    },
    "__v" : 0
}

One of the biggest advantages of using a NoSQL database server such as MongoDB is that it has a dynamic schema system, allowing records in a collection to be completely different from one another.

Some advantages of working with MongoDB are:

  • Dynamic schema design
  • Fast querying and indexing
  • Aggregate framework
  • Sharding and replication

In addition, as MongoDB was written using a JSON-like document structure, JavaScript becomes a powerful tool when working with queries and the interactive shell mongo. Like Node, MongoDB is also built for high performance, making it a great counterpart for building ever demanding, high traffic web and mobile applications. Depending on your exact needs, MongoDB may or may not be the right solution for your application. You should truly weigh the pros and cons of each technology before making a decision to determine which technology is right for you.

Node and MongoDB in the wild

Both Node and MongoDB are extremely popular and active in the development community. This is true for enterprises as well. Some of the biggest names in the Fortune 500 space have fully embraced Node to power their web applications. This is due in large part to the asynchronous nature of Node, which makes it a great alternative for high traffic, high IO applications such as e-commerce websites and mobile applications.

The following is just a small list of some big companies that are working with Node:

  • PayPal
  • LinkedIn
  • eBay
  • Walmart
  • Yahoo!
  • Microsoft
  • Dow Jones
  • Uber
  • New York Times

MongoDB's use in the enterprise sector is equally as impressive and wide reaching with an increasing number of companies adopting the leading NoSQL database server, such as:

  • Cisco
  • Craigslist Inc.
  • Forbes
  • FourSquare
  • Intuit
  • McAfee
  • MTV
  • MetLife
  • Shutterfly
  • Under Armour

What to expect from this book

The remainder of this book is going to be a guided tour that walks you through creating a complete data-driven website. The website we create will feature almost every aspect of a typical large-scale web development project. At its core, it will be powered by Node.js using a popular third-party framework called Express, and it will persist data using MongoDB.

In the first few chapters, we will cover the groundwork involved in getting the core of the server up and serving content. This includes configuring your environment so you are up and running with Node and MongoDB, and a basic introduction to the core concepts of both technologies. Then, we will write a web server from scratch powered by ExpressJS that will handle serving all of the necessary files for the website. From there, we will work with the Handlebars template engine to serve both static and dynamic HTML webpages. Diving deeper, we will make the application persistent by adding a data layer where the records for the website will be saved and retrieved via a MongoDB server. We will cover writing a RESTful API so that third parties can interact with your application. Finally, we will go into detail examining how to write and execute tests for all of your code.

Wrapping up, we will take a brief detour as we examine some popular, emerging frontend technologies that are becoming increasingly popular while writing single-page applications. These technologies include Backbone.js, Angular, and Ember.js.

Last but not least, we will go into details of how to deploy your new website to the Internet using popular cloud-based hosting services such as Heroku and Amazon Web Services.

Summary

In this chapter, we reviewed what is to be expected throughout the remainder of this book. We discussed the amazing current state of JavaScript and how it can be used to power the full stack of a web application. Not that you needed any convincing in the first place, but I hope you're excited and ready to get started writing web applications using Node.js and MongoDB!

Next up, we will set up your development environment and get you up and running with Node, MongoDB, and npm as well as write and launch a quick first Node app that uses MongoDB!

Left arrow icon Right arrow icon

Description

This book is designed for developers of any skill level that want to get up and running using Node.js and MongoDB to build full featured web applications. A basic understanding of JavaScript and HTML is the only requirement for this book.

What you will learn

  • Set up a development environment and install Node.js and MongoDB
  • Write and configure a web server using Node.js powered by the Express.js framework
  • Build dynamic HTML pages using the Handlebars template engine
  • Persist application data using MongoDB and Mongoose ODM
  • Create and consume RESTful APIs
  • Test your code using automated testing tools
  • Deploy to the cloud using services such as Heroku, Amazon Web Services, and Microsoft Azure
  • Explore Single Page Application frameworks to take your web applications to the next level

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 25, 2014
Length: 294 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987313
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 25, 2014
Length: 294 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987313
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Web Development with MongoDB and Node.js
€36.99
Node.js Design Patterns
€41.99
MEAN Web Development
€41.99
Total 120.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Welcome to JavaScript in the Full Stack Chevron down icon Chevron up icon
2. Getting Up and Running Chevron down icon Chevron up icon
3. Node and MongoDB Basics Chevron down icon Chevron up icon
4. Writing an Express.js Server Chevron down icon Chevron up icon
5. Dynamic HTML with Handlebars Chevron down icon Chevron up icon
6. Controllers and View Models Chevron down icon Chevron up icon
7. Persisting Data with MongoDB Chevron down icon Chevron up icon
8. Creating a RESTful API Chevron down icon Chevron up icon
9. Testing Your Code Chevron down icon Chevron up icon
10. Deploying with Cloud-based Services Chevron down icon Chevron up icon
11. Single Page Applications with Popular Frontend Frameworks Chevron down icon Chevron up icon
12. Popular Node.js Web Frameworks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(12 Ratings)
5 star 58.3%
4 star 16.7%
3 star 0%
2 star 16.7%
1 star 8.3%
Filter icon Filter
Top Reviews

Filter reviews by




Burak AKIN Oct 14, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am not a professional coder or programmer. My job is health related. I code as a hobby. This book is what you need to get into development with Mongo and Nodejs. The example application inside the book will form a nice real time app also. The concepts are very well explained without boring you. Even a person like me can understand and code everything.
Amazon Verified review Amazon
Amazon Customer Oct 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a quick read to get you quickly running building any web applications with a MongoDB backend. The examples are easy to follow and quick to convert to a real scenario web application. Many extras beyond teaching the node and mongo lesson.
Amazon Verified review Amazon
Airam Oct 29, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Writing RESTful services in Nodejs can be as simple as glueing modules. Internet is plenty of Node.js middleware. To achieve so, you first need to learn the basics.It's better to have some previous knowledge of Javascript before reading this book as Web Development with MongoDB and Node.js has a tiny introduction to Javascript and Node.js.The book explains how to scaffold web applications through full coded examples. Middleware is the key of being highly productive and the book uses and explains the most well-known modules. You'll find out a big example split into several chapters that is a clone of a popular social image-sharing site that will show you things such as:Express: handle routing, middleware injection, ...Connect: a suite of middleware for multiple things. In the book Connect is used to deal with json, cookies, logging, parsing, encoding, HTTP method support, handling errors ...Handlebars: apart from explaining the basics of this template engine, it also shows how to build html layouts, partial views which prevent code duplication and helpers used for injecting functions at the time of rendering.And all this is wired up with MongoDB which is a NoSQL database. You'll learn the really basics of CRUD operations over Mongo (Create, Retrieve, Update and Delete). But Mongo is such simple that it really doesn't need further explanation other than seeing the API definition. This makes the book swift and faster to read. As it's already a tradition with Mongo and Javascript, it also involves Mongoose. Mongoose introduces schemas and models, that is to say built-in types, field restrictions and validation.The book culminates with four miscellaneous chapters. A chapter dedicated to testing using Behavior Driven Development (Mocha, Chai.js, Sinon.js, Proxyquire). Another chapter that gathers some web services (like Heroku, Amazon, Digital Ocean, Nodejitsu and Microsoft Azure) and tells how to deploy your nodejs web-apps. And finally, the last two chapters reviews front-end frameworks like: Backbone.js, Ember.js, Angular.js; and Node.js frameworks like Meteor, Sails, hapi, Koa or Flatiron.At the end of the book you will be more likely to start developing your own RESTful services as Node.js makes things simple and this book covers really common problems.You can get your copy of Web Development with MongoDB and Node.js right here!
Amazon Verified review Amazon
Steven Aug 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Jason is a MEAN expert! Great real world examples and spoken in a language that anyone can understand. Highly recommend this book to anyone who is spiking the Mongo/Express/Angular/Node stack to build engaging single page apps in JS.
Amazon Verified review Amazon
Sergiy Pylypets Oct 20, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book contains hands-on instructions for getting started with development of complete interactive Web sites using up-to-day Web technologies. It empowers readers with practical knowledge of Node.js and MongoDB. The first chapter describes new concepts of Web development, which were introduced with Node.js. From chapter 4, Writing an Express.js Server, we are guided to create a sample Web application, which includes all main functionality of real-world applications, based on the usage of Express.js Web framework. Chapter 9, Testing Your Code, introduces the tools and techniques to write automated tests for Node.js code. Chapter 10, Deploying with Cloud-based Services, provides detailed instructions for Cloud-based deployment and hosting of Web applications. In chapter 12, Popular Node.js Web Frameworks, author reviews other Web frameworks, including recently-emerged ones, and analyzes their advantages, drawbacks and cases of usage. The book is written by clear and concise language. The content includes a lot of code fragments, schemes, and screenshots. Each chapter ends with Summary section, which recapitulates all the main topics of the chapter. There are several reminder sections, like A JavaScript Primer, which recalls JavaScript basics, or What is an API, which discusses API development concepts. All chapters include links to additional information resources. For all main technologies being discussed, detailed step-by-step installation instructions are provided for Windows, Mac OS, and Linux environment, which greatly stimulate readers to download and try all the stuff. I think that this book can be useful for all Web developers, who want to use modern technologies for creating powerful and scalable Web applications.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.