SlideShare a Scribd company logo
Developing a Basic REST API from
Scratch Using TDD
Valeri Karpov
Node.js Engineer, MongoDB
www.thecodebarbarian.com
github.com/vkarpov15
@code_barbarian
*
What is this talk about?
•MongoDB is great for storing web/mobile app data
•So let’s build a REST API using Node.js!
•+ learn a bit about test-driven dev with Node.js
•+ learn two MongoDB schema design principles
•Server-side only - just JSON, no HTML
•No AngularJS part, focus more on MongoDB
•Upcoming EdX course
*
Overview
•Part 1: Shopping Cart Application
–Search for products
–Add them to your cart
–Check out with Stripe
•Part 2: Using the Mongoose ODM
•Part 3: Schema Design
•Part 4: Building an API with the Express framework
•Part 5: Testing with Mocha + Superagent
*
Part 1: What Does the App Do?
*
What Does the App Do?
*
What Does the App Do?
*
App Structure
•"Bad programmers worry about the code. Good
programmers worry about data structures and their
relationships." - Linus Torvalds
•3 schemas for 3 collections:
•Products
•Categories
•Users
*
Schema Relationships
•Product belongs to one or more categories
•Users can have multiple products in their cart
•Representing relationships in MongoDB is tricky
•But that’s what mongoose is for
*
Part 2: Using the Mongoose ODM
•“Object document mapper” (like ORM, but for
MongoDB)
•“MongoDB object modeling designed to work in an
asynchronous environment”
•Written for Node.js
•Provides schema validation, pseudo-JOINs, etc.
*
Brief Overview of Node.js
•require()
• Async I/O
*
What Does Async Mean?
Register event
handler
In node.js, you don’t execute I/O imperatively.
You register a callback to execute when the I/O is
done
Prints before
“done reading”
*
Your First Mongoose Schema
matches X@Y.Z
*
Using Your Schema
Create User
Save user to MongoDB
Load user from MongoDB
Print user to stdout
*
Part 2 Takeaways
•Mongoose provides several neat features
–Model part of MVC
–Default values
–Schema validation and declarative schema design
*
Part 3: Schema Design
•3 schemas:
–Product
–Category
–User
•Going to use mongoose to define schemas
•Will use a couple key schema design principles
*
Product Schema
*
Product Schema in Action
*
Category Schema
*
Category Schema Queries
•What categories are descendants of “Electronics”?
•
•What categories are children of “Non-Fiction”?
•
•What categories are ancestors of “Phones”?
*
Product + Category Schemas
*
Category Schema Takeaways
•Queries in MongoDB should be simple
•Strive for minimal data transformation by server
•“Store what you query for”
•“If you need [the aggregation framework in a heavily
used API endpoint], you're screwed anyway, and should
fix your program.” - Linus Torvalds
•Good for performance and developer sanity
*
User Schema
User’s cart as an array
of ObjectIds...
*
Principle of Least Cardinality
•Product and user = many-to-many relationship
•Don’t necessarily need a mapping table
•User won’t have 1000s of products in cart
•Can represent relationship as array in user since
one side is small
•If one side of many-to-many is bounded and/or
small, it is a good candidate for embedding
•Arrays that grow without bound are an
antipattern!
–16mb document size limit
–network overhead
*
Part 4: The Express Framework
•Most popular Node.js web framework
•Simple, pluggable, and fast
•Great tool for building REST APIs
*
Your First Express App
Route Parameter
*
What is REST?
•Representational State Transfer
•HTTP request -> JSON HTTP response
•Business logic on top of MongoDB schemas
–Access control, emails, analytics, etc.
*
Structuring Your REST API
*
GET /category/id/:id
Find Category
Error handling
Output JSON
*
GET /category/parent/:id
*
GET /product/category/:id
*
Adding Products to User’s Cart
•Recall cart is an array of products
*
Adding Products to User’s Cart
Get cart from HTTP request
Overwrite user’s cart
Let mongoose handle
casting and validating data
*
PUT /me/cart Takeaways
•Mongoose lets you be lazy
•Access control using subdocs
*
Bonus: Stripe Checkout
Create a Stripe charge with the npm ‘stripe’ module
*
Bonus: Stripe Checkout
Error handling
Empty user cart
on success
*
Part 4 Takeaways
•Express REST API on top of mongoose
–Access control
–Business logic
–Define what operations user can take on database
•Mongoose casting and validation for APIs
*
Part 5: Test-Driven Development
•Building an API is tricky
•Lots of different error conditions
•Express has a lot of magic under the hood
*
NodeJS Concurrency and Testing
•Node.js runs in an event loop
•Single threaded
•Can run client and server on same thread!
–Client sends HTTP request
–Client registers a callback awaiting the result
–Server’s “on HTTP request” event handler is triggered
–Server sends response, continues waiting for events
–Client’s callback gets fired
•Test server end-to-end
*
Superagent
•NodeJS HTTP client
•Isomorphic: runs in both browser and NodeJS
•Same author as Express
*
Mocha
•Testing Framework for NodeJS
•Same author as Express
•BDD-style syntax
–describe() -> test suite
–it() -> individual test
*
Setting Up Category API Tests
*
Testing GET /category/id/:id
*
Part 5 Takeaways
•NodeJS concurrency makes testing easy
•Not just unit tests - full E2E for your REST API
•Can manipulate database and make arbitrary
HTTP requests
*
•Upcoming EdX Video Course
•Slides on http://www.slideshare.net/vkarpov15
•Looking for beta testers! Sign up for notifications
–http://goo.gl/forms/0ckaJ4YvJN
•Interested in learning about AngularJS?
–Professional AngularJS on Amazon
•More NodeJS+MongoDB content at:
–www.thecodebarbarian.com
–Twitter: @code_barbarian
Thanks for Listening!
Webinar: Get Started with the MEAN Stack

More Related Content

What's hot (20)

PPTX
Webinar: Simplifying the Database Experience with MongoDB Atlas
MongoDB
 
PPTX
What's new in MongoDB 3.6?
MongoDB
 
PDF
MongoDB Launchpad 2016: MongoDB 3.4: Your Database Evolved
MongoDB
 
PPTX
How Thermo Fisher is Reducing Data Analysis Times from Days to Minutes with M...
MongoDB
 
PDF
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB
 
PDF
MongoDB World 2019: Securing Application Data from Day One
MongoDB
 
PPTX
Scaling and Transaction Futures
MongoDB
 
PDF
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB
 
PDF
Building LinkedIn's Learning Platform with MongoDB
MongoDB
 
PDF
MongoDB Stitch Introduction
MongoDB
 
PPTX
A Free New World: Atlas Free Tier and How It Was Born
MongoDB
 
PPTX
Introduction to MERN Stack
Surya937648
 
PPTX
Experian Health: Moving Universal Identity Manager from ANSI SQL to MongoDB
MongoDB
 
PPTX
What's New In MongoDB 3.6
MongoDB
 
PPTX
Building Your First App with MongoDB Stitch
MongoDB
 
PPTX
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
MongoDB
 
PPTX
Transforming a Large Mission-Critical E-Commerce Platform from a Relational A...
MongoDB
 
PDF
MongoDB at Gilt Groupe
MongoDB
 
PDF
The Path to Truly Understanding your MongoDB Data
MongoDB
 
PDF
MongoDB World 2019: Mastering MongoDB in Kubernetes
MongoDB
 
Webinar: Simplifying the Database Experience with MongoDB Atlas
MongoDB
 
What's new in MongoDB 3.6?
MongoDB
 
MongoDB Launchpad 2016: MongoDB 3.4: Your Database Evolved
MongoDB
 
How Thermo Fisher is Reducing Data Analysis Times from Days to Minutes with M...
MongoDB
 
MongoDB World 2019: Fast Machine Learning Development with MongoDB
MongoDB
 
MongoDB World 2019: Securing Application Data from Day One
MongoDB
 
Scaling and Transaction Futures
MongoDB
 
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB
 
Building LinkedIn's Learning Platform with MongoDB
MongoDB
 
MongoDB Stitch Introduction
MongoDB
 
A Free New World: Atlas Free Tier and How It Was Born
MongoDB
 
Introduction to MERN Stack
Surya937648
 
Experian Health: Moving Universal Identity Manager from ANSI SQL to MongoDB
MongoDB
 
What's New In MongoDB 3.6
MongoDB
 
Building Your First App with MongoDB Stitch
MongoDB
 
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
MongoDB
 
Transforming a Large Mission-Critical E-Commerce Platform from a Relational A...
MongoDB
 
MongoDB at Gilt Groupe
MongoDB
 
The Path to Truly Understanding your MongoDB Data
MongoDB
 
MongoDB World 2019: Mastering MongoDB in Kubernetes
MongoDB
 

Viewers also liked (20)

PPTX
Back to Basics Webinar 1: Introduction to NoSQL
MongoDB
 
PPTX
Webinar: Gaining Insights into MongoDB with MongoDB Cloud Manager and New Relic
MongoDB
 
PPTX
Transitioning from SQL to MongoDB
MongoDB
 
PPTX
Modern Databases for Modern Application Architectures: The Next Wave of Desig...
MongoDB
 
PDF
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
PPTX
An Introduction to MongoDB Compass
MongoDB
 
PPTX
Webinar: Back to Basics: Thinking in Documents
MongoDB
 
PPTX
Webinar: Live Data Visualisation with Tableau and MongoDB
MongoDB
 
PPTX
MongoDB Days Silicon Valley: Implementing Graph Databases with MongoDB
MongoDB
 
PPTX
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
MongoDB
 
PPTX
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
PPTX
Back to Basics Webinar 1: Introduction to NoSQL
MongoDB
 
PPTX
MongoDB Days UK: Building an Enterprise Data Fabric at Royal Bank of Scotland...
MongoDB
 
PDF
Using MongoDB as a high performance graph database
Chris Clarke
 
PPT
Introduction to MongoDB
Ravi Teja
 
PDF
Introduction to MongoDB
Mike Dirolf
 
PDF
Mongodb and Totsy: An e-commerce case study
Mitch Pirtle
 
KEY
The Ruby/mongoDB ecosystem
Harold Giménez
 
PDF
MongoDB World 2016: Poster Sessions eBook
MongoDB
 
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
Back to Basics Webinar 1: Introduction to NoSQL
MongoDB
 
Webinar: Gaining Insights into MongoDB with MongoDB Cloud Manager and New Relic
MongoDB
 
Transitioning from SQL to MongoDB
MongoDB
 
Modern Databases for Modern Application Architectures: The Next Wave of Desig...
MongoDB
 
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
An Introduction to MongoDB Compass
MongoDB
 
Webinar: Back to Basics: Thinking in Documents
MongoDB
 
Webinar: Live Data Visualisation with Tableau and MongoDB
MongoDB
 
MongoDB Days Silicon Valley: Implementing Graph Databases with MongoDB
MongoDB
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
MongoDB
 
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
Back to Basics Webinar 1: Introduction to NoSQL
MongoDB
 
MongoDB Days UK: Building an Enterprise Data Fabric at Royal Bank of Scotland...
MongoDB
 
Using MongoDB as a high performance graph database
Chris Clarke
 
Introduction to MongoDB
Ravi Teja
 
Introduction to MongoDB
Mike Dirolf
 
Mongodb and Totsy: An e-commerce case study
Mitch Pirtle
 
The Ruby/mongoDB ecosystem
Harold Giménez
 
MongoDB World 2016: Poster Sessions eBook
MongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
Ad

Similar to Webinar: Get Started with the MEAN Stack (20)

PDF
MongoDB MEAN Stack Webinar October 7, 2015
Valeri Karpov
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
PDF
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
PDF
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
PDF
CMPE282_009994036_PROJECT_REPORT
Sandyarathi Das
 
PDF
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Mark Leusink
 
PDF
MEAN Stack Workshop at Node Philly, 4/9/14
Valeri Karpov
 
PDF
JS-IL: Getting MEAN in 1 Hour
Valeri Karpov
 
PPTX
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB
 
PPTX
Rapid Application Development with MEAN Stack
Avinash Kaza
 
PDF
Designing your API Server for mobile apps
Mugunth Kumar
 
PPTX
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
PPTX
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 
PPTX
Fast Track introduction to ASP.NET MVC
Ankit Kashyap
 
PPTX
Building Your First App with MongoDB
MongoDB
 
PPTX
AngularJS One Day Workshop
Shyam Seshadri
 
PDF
Asp 1a-aspnetmvc
Fajar Baskoro
 
PDF
Aspnetmvc 1
Fajar Baskoro
 
PPTX
SignalR with ASP.NET MVC 6
Tung Nguyen Thanh
 
MongoDB MEAN Stack Webinar October 7, 2015
Valeri Karpov
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
CMPE282_009994036_PROJECT_REPORT
Sandyarathi Das
 
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Mark Leusink
 
MEAN Stack Workshop at Node Philly, 4/9/14
Valeri Karpov
 
JS-IL: Getting MEAN in 1 Hour
Valeri Karpov
 
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB
 
Rapid Application Development with MEAN Stack
Avinash Kaza
 
Designing your API Server for mobile apps
Mugunth Kumar
 
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 
Fast Track introduction to ASP.NET MVC
Ankit Kashyap
 
Building Your First App with MongoDB
MongoDB
 
AngularJS One Day Workshop
Shyam Seshadri
 
Asp 1a-aspnetmvc
Fajar Baskoro
 
Aspnetmvc 1
Fajar Baskoro
 
SignalR with ASP.NET MVC 6
Tung Nguyen Thanh
 
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB
 
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB
 
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB
 
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB
 
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB
 
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB
 
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB
 
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB
 
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB
 
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB
 
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB
 
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB
 
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB
 
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB
 

Recently uploaded (20)

PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PPTX
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Survival Models: Proper Scoring Rule and Stochastic Optimization with Competi...
Paris Women in Machine Learning and Data Science
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Survival Models: Proper Scoring Rule and Stochastic Optimization with Competi...
Paris Women in Machine Learning and Data Science
 

Webinar: Get Started with the MEAN Stack

  • 1. Developing a Basic REST API from Scratch Using TDD Valeri Karpov Node.js Engineer, MongoDB www.thecodebarbarian.com github.com/vkarpov15 @code_barbarian
  • 2. * What is this talk about? •MongoDB is great for storing web/mobile app data •So let’s build a REST API using Node.js! •+ learn a bit about test-driven dev with Node.js •+ learn two MongoDB schema design principles •Server-side only - just JSON, no HTML •No AngularJS part, focus more on MongoDB •Upcoming EdX course
  • 3. * Overview •Part 1: Shopping Cart Application –Search for products –Add them to your cart –Check out with Stripe •Part 2: Using the Mongoose ODM •Part 3: Schema Design •Part 4: Building an API with the Express framework •Part 5: Testing with Mocha + Superagent
  • 4. * Part 1: What Does the App Do?
  • 5. * What Does the App Do?
  • 6. * What Does the App Do?
  • 7. * App Structure •"Bad programmers worry about the code. Good programmers worry about data structures and their relationships." - Linus Torvalds •3 schemas for 3 collections: •Products •Categories •Users
  • 8. * Schema Relationships •Product belongs to one or more categories •Users can have multiple products in their cart •Representing relationships in MongoDB is tricky •But that’s what mongoose is for
  • 9. * Part 2: Using the Mongoose ODM •“Object document mapper” (like ORM, but for MongoDB) •“MongoDB object modeling designed to work in an asynchronous environment” •Written for Node.js •Provides schema validation, pseudo-JOINs, etc.
  • 10. * Brief Overview of Node.js •require() • Async I/O
  • 11. * What Does Async Mean? Register event handler In node.js, you don’t execute I/O imperatively. You register a callback to execute when the I/O is done Prints before “done reading”
  • 13. * Using Your Schema Create User Save user to MongoDB Load user from MongoDB Print user to stdout
  • 14. * Part 2 Takeaways •Mongoose provides several neat features –Model part of MVC –Default values –Schema validation and declarative schema design
  • 15. * Part 3: Schema Design •3 schemas: –Product –Category –User •Going to use mongoose to define schemas •Will use a couple key schema design principles
  • 19. * Category Schema Queries •What categories are descendants of “Electronics”? • •What categories are children of “Non-Fiction”? • •What categories are ancestors of “Phones”?
  • 21. * Category Schema Takeaways •Queries in MongoDB should be simple •Strive for minimal data transformation by server •“Store what you query for” •“If you need [the aggregation framework in a heavily used API endpoint], you're screwed anyway, and should fix your program.” - Linus Torvalds •Good for performance and developer sanity
  • 22. * User Schema User’s cart as an array of ObjectIds...
  • 23. * Principle of Least Cardinality •Product and user = many-to-many relationship •Don’t necessarily need a mapping table •User won’t have 1000s of products in cart •Can represent relationship as array in user since one side is small •If one side of many-to-many is bounded and/or small, it is a good candidate for embedding •Arrays that grow without bound are an antipattern! –16mb document size limit –network overhead
  • 24. * Part 4: The Express Framework •Most popular Node.js web framework •Simple, pluggable, and fast •Great tool for building REST APIs
  • 25. * Your First Express App Route Parameter
  • 26. * What is REST? •Representational State Transfer •HTTP request -> JSON HTTP response •Business logic on top of MongoDB schemas –Access control, emails, analytics, etc.
  • 31. * Adding Products to User’s Cart •Recall cart is an array of products
  • 32. * Adding Products to User’s Cart Get cart from HTTP request Overwrite user’s cart Let mongoose handle casting and validating data
  • 33. * PUT /me/cart Takeaways •Mongoose lets you be lazy •Access control using subdocs
  • 34. * Bonus: Stripe Checkout Create a Stripe charge with the npm ‘stripe’ module
  • 35. * Bonus: Stripe Checkout Error handling Empty user cart on success
  • 36. * Part 4 Takeaways •Express REST API on top of mongoose –Access control –Business logic –Define what operations user can take on database •Mongoose casting and validation for APIs
  • 37. * Part 5: Test-Driven Development •Building an API is tricky •Lots of different error conditions •Express has a lot of magic under the hood
  • 38. * NodeJS Concurrency and Testing •Node.js runs in an event loop •Single threaded •Can run client and server on same thread! –Client sends HTTP request –Client registers a callback awaiting the result –Server’s “on HTTP request” event handler is triggered –Server sends response, continues waiting for events –Client’s callback gets fired •Test server end-to-end
  • 39. * Superagent •NodeJS HTTP client •Isomorphic: runs in both browser and NodeJS •Same author as Express
  • 40. * Mocha •Testing Framework for NodeJS •Same author as Express •BDD-style syntax –describe() -> test suite –it() -> individual test
  • 43. * Part 5 Takeaways •NodeJS concurrency makes testing easy •Not just unit tests - full E2E for your REST API •Can manipulate database and make arbitrary HTTP requests
  • 44. * •Upcoming EdX Video Course •Slides on http://www.slideshare.net/vkarpov15 •Looking for beta testers! Sign up for notifications –http://goo.gl/forms/0ckaJ4YvJN •Interested in learning about AngularJS? –Professional AngularJS on Amazon •More NodeJS+MongoDB content at: –www.thecodebarbarian.com –Twitter: @code_barbarian Thanks for Listening!

Editor's Notes

  • #45: Customers (not just users)