Mongoose for Application Development
By Simon Holmes
4.5/5
()
About this ebook
Simon Holmes
Simon Holmes has been a full-stack developer since the late 1990s, manages the European Solutions Engineering team for LivePerson and runs Full Stack Training Ltd.
Related to Mongoose for Application Development
Related ebooks
Deploying Node.js Rating: 5 out of 5 stars5/5Web Development with MongoDB and NodeJS - Second Edition Rating: 0 out of 5 stars0 ratingsWeb Development with MongoDB and Node.js Rating: 0 out of 5 stars0 ratingsNode.js By Example Rating: 2 out of 5 stars2/5Mastering Node.js Rating: 1 out of 5 stars1/5Modern JavaScript Applications Rating: 0 out of 5 stars0 ratingsExpress Web Application Development Rating: 3 out of 5 stars3/5RESTful Web API Design with Node.js - Second Edition Rating: 1 out of 5 stars1/5Go Programming Blueprints Rating: 0 out of 5 stars0 ratingsASP.NET Web API Security Essentials Rating: 0 out of 5 stars0 ratingsASP.NET Core 3 and React: Hands-On full stack web development using ASP.NET Core, React, and TypeScript 3 Rating: 0 out of 5 stars0 ratingsBuilding a RESTful Web Service with Spring Rating: 5 out of 5 stars5/5Getting Started with React Rating: 0 out of 5 stars0 ratingsMastering Symfony Rating: 0 out of 5 stars0 ratingsPHP 7 Programming Blueprints Rating: 0 out of 5 stars0 ratingsBuilding Scalable Apps with Redis and Node.js Rating: 0 out of 5 stars0 ratingsAngularJS Deployment Essentials Rating: 0 out of 5 stars0 ratingsLearning Docker Rating: 5 out of 5 stars5/5MEAN Web Development Rating: 5 out of 5 stars5/5Learning Node.js for Mobile Application Development Rating: 0 out of 5 stars0 ratingsMongoDB High Availability Rating: 5 out of 5 stars5/5Learning PHP Data Objects Rating: 5 out of 5 stars5/5Learning Angular for .NET Developers Rating: 0 out of 5 stars0 ratingsLearning PHP 7 Rating: 4 out of 5 stars4/5Go Programming Blueprints - Second Edition Rating: 5 out of 5 stars5/5Mastering Spring 5.0 Rating: 5 out of 5 stars5/5Web Application Development with MEAN Rating: 0 out of 5 stars0 ratingsAngularJS Web Application Development Blueprints Rating: 0 out of 5 stars0 ratingsMastering JavaScript Design Patterns Rating: 4 out of 5 stars4/5
Internet & Web For You
More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Wireless Hacking 101 Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5Introduction to Internet Scams and Fraud: Credit Card Theft, Work-At-Home Scams and Lottery Scams Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsRemote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5The Internet Is Not What You Think It Is: A History, a Philosophy, a Warning Rating: 4 out of 5 stars4/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Ultimate Guide for Being Anonymous: Hacking the Planet, #4 Rating: 5 out of 5 stars5/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5200+ Ways to Protect Your Privacy: Simple Ways to Prevent Hacks and Protect Your Privacy--On and Offline Rating: 0 out of 5 stars0 ratingsEverybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Learn HTML Programming in 7 Days: Ultimate Beginners Guide to Build and Design Your Own Website Rating: 4 out of 5 stars4/5Lying and Lie Detection: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsHow To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsHow To Start A Podcast Rating: 4 out of 5 stars4/5No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5
Reviews for Mongoose for Application Development
2 ratings0 reviews
Book preview
Mongoose for Application Development - Simon Holmes
Table of Contents
Mongoose for Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
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. Introducing Mongoose to the Technology Stack
The technology stack – Node.js, npm, MongoDB, and Express
The language and the server – JavaScript and Node
Single-threaded versus multithreaded
Blocking versus non-blocking code
JavaScript callbacks
Running the callback
A Node.js example
The database – MongoDB
The framework – Express
What Mongoose is all about
What is Mongoose good for?
What Mongoose is not ideally suited for
The cornerstones of Mongoose
Mongoose schemas
Mongoose models
Installing the full stack
Installing the prerequisites
Installing Node.js
Installing npm
Installing MongoDB
Installing Express.js
Installing Mongoose
Direct installation into project
Using project dependencies – package.json
Creating a project
Summary
2. Establishing a Database Connection
Mongoose default connection
Using multiple connections
About the connection string
Setting the port
Specifying a database user
Connection options
Closing the connection
Calling the close command
Closing when the Node process ends
Connection events
Connecting our project
Creating the connection
Catching the events
Opening the connection at application start
Creating the database
Summary
3. Schemas and Models
Introducing schemas
Field sizes
Data types allowed in schemas
String
Number
Date
Boolean
Buffer
ObjectId
Mixed
Tracking changes to Mixed type
Array
Warning – array defined as mixed type
Custom SchemaTypes
Where to write the schemas
Writing a schema
Modifying an existing schema
Setting a default value
Only allowing unique entries
Our final User schema
What's that __v
thing?
Why is this needed?
Defining the Project schema
Improving the Project schema
Building models
Instances
Interacting with instances
Finding a single instance
Finding many instances
Considerations when choosing your model name
Setting the collection name
Overriding the collection name in the schema
Overriding the collection name in the model
Building models from our schemas
Our complete code
Summary
4. Interacting with Data – an Introduction
Model methods and instance methods
Setting up the project
Code structure
Adding the routes files
Tying the routes to Mongoose models
URLs and routes
Routes for user management
Routes for project management
Summary
5. Interacting with Data – Creation
Creating an instance
Adding data to the instance
Saving an instance
Using the saved data
Creating and saving database entry in one step
Chaining methods
The Model.create() method
CRUD – create data
Adding a new user form
Adding the Jade template
Linking the view to the URL
Adding the create user function
Error trapping
Creating a user session
Displaying the confirmation page
Try it out!
Adding create project functionality
Routes
New files and functions
Summary
6. Interacting with Data – Reading, Querying, and Finding
Approaches to find and read data
Using the QueryBuilder
Single query operation
Static helper methods – finding data
CRUD – reading user and project data
findOne() – finding a single user
Login form
Login action
Housekeeping – adding homepage links
Try it out!
find() – finding a list of projects and returning JSON to AJAX
Creating a new static find method
Setting up the route
Updating the view
Building the AJAX call
Try it out!
findByld() – finding a single project
Route setup
Creating the view
Summary
7. Interacting with Data – Updating
Model helper methods
Building the commands
Which method to choose
The catch
The three-step find-edit-save approach
CRUD – editing users and projects
Tracking user login
Editing the current user
Routes in use
Setting up the form
Setting up the controllers
Committing the edit
Editing projects
Routes
New files and functions
Summary
8. Interacting with Data – Deleting
Deleting data
CRUD – deleting user and projects
The Are you sure
page
Deleting the user
Improving on this
Deleting individual projects
Routes
New files and functions
Summary
9. Validating Data
Mongoose validation – the basics
Default validators
All SchemaTypes
Number SchemaType
String SchemaType
Understanding validation errors
Doing it your way – create custom validation
Single function – no custom error message
Returning a custom error message
Validating a regular expression
Taking the messages out of the schema
Using multiple re-usable validators
Non-blocking, asynchronous validation
Extending Mongoose validation
Adding validation to our project
Summary
10. Complex Schemas
Population – references to other collections
Defining data for population
Saving population references
Retrieving populated data
Querying to return a subset of results
Populating into multiple parent items
Subdocuments
Creating subdocuments
Saving and validation
Retrieving subdocuments
Accessing a specific subdocument
Deleting subdocuments
Data management when modifying existing schemas
Summary
11. Plugins – Re-using Code
Reusable schema plugins
Creating a schema plugin
Applying the plugin to an existing schema
Using an external file
Using schema middleware
Not just for plugins
Sharing with the community
Summary
Index
Mongoose for Application Development
Mongoose for Application Development
Copyright © 2013 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: August 2013
Production Reference: 1200813
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-819-5
www.packtpub.com
Cover Image by Abhishek Pandey (<abhishek.pandey1210@gmail.com>)
Credits
Author
Simon Holmes
Reviewers
Alexandru Vlăduțu
Robert Klep
David Harvey
Acquisition Editor
Grant Mizen
Commisioning Editor
Llewellyn Rozario
Technical Editor
Akashdeep Kundu
Project Coordinator
Joel Goveya
Proofreader
Mario Cecere
Indexer
Hemangini Bari
Production Coordinator
Aditi Gajjar
Cover Work
Aditi Gajjar
About the Author
Simon Holmes started his journey as a web developer in late 1990s. He built his first website for a project at university and soon saw what the industry had to offer when he promptly sold it! Following university, Simon worked his way through the ranks of design agency life, learning the skills of becoming a full-stack web developer. From server management and database design to building dynamic, UIs from Photoshop files, it all fell under Simon's remit. Having witnessed first-hand the terrible JavaScript code so prevalent in the early 2000s Simon is very much enjoying its resurgence as a powerful, structured language. Simon now works in SaaS, which is very heavy on the JavaScript.
Firstly I would like to thank my wife Sally for taking increased duties with our two lovely young daughters Eri and Bel, affording me some peace and quiet in which to code and write. Thanks also to Andreas Soellner for his feedback and encouragement throughout the process, and technical reviewers David Harvey of Vyclone Inc., Robert Klep, and Alexandru Vlăduțu. I also wish to express my thanks to the team at Packt Publishing who have been open and helpful from start to finish. Not forgetting of course Aaron Heckman who created Mongoose and continues to maintain, support, and push it forward.
About the Reviewers
David Harvey has built tools for more than twenty five years for developers, architectural infrastructure for investment banks, and high-end music software. He has formed and led teams in organizations of all sizes, and has taught, consulted, and presented on object technology, patterns and agile software development. He is currently the CTO at Vyclone Inc., delivering ground-breaking multi-angle video technology on mobile and cloud platforms.
Robert Klep is a freelance frontend and backend web developer from 's-Hertogenbosch, the Netherlands, with more than 17 years experience. Lately, Robert has been focusing more on JavaScript and Node.js development. He has used Mongoose extensively in several projects. He was the winner of the 0th Annual Obfuscated Perl Contest in 1996.
Alexandru Vlăduțu is a JavaScript developer at a company in Bucharest, Romania. He started creating applications with PHP five years ago, but after finding out about server-side JavaScript with Node.js he never had to switch technologies again. You may have seen him answering questions on stackoverflow.com under the nickname alessioalex, where he is in the top three overall answerers for tags like Node.js, Express, Mongoose, or Socket.IO. By day he battles cross browser compatibility issues, but by night he brings together embedded databases, servers, and caching layers into single applications using the good parts of JavaScript. Aside from the geeky stuff, he enjoys spending time with his wife.
I would like to thank the Node.js community for being so friendly and