Web Development with Mongodb and Node Third Edition
Total Page:16
File Type:pdf, Size:1020Kb
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: [email protected] "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 forward-chaining 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-a-Service 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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] 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. https://www.packtpub.com/mapt 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 https://www.amazon.com/dp/1788395085. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. 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