SlideShare a Scribd company logo
Developing and Testing a MongoDB
and Node.js REST API
Valeri Karpov
Node.js Engineer, MongoDB
www.thecodebarbarian.com
github.com/vkarpov15
@code_barbarian
*
What is this talk about?
•Briefly introduce MongoDB and Node.js
•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
•Upcoming EdX course
*
What is MongoDB?
•Document database - store objects, not columns
•Often better* performance
• Better data locality than RDBMS for 1 query vs 5 JOINs
*
What is MongoDB?
•Easier ops
• No need to set up databases, tables, schemas, etc.
• Run one executable, you now have a working db
• MongoDB Cloud Manager and Ops Manager
•Developer sanity
• In my experience, easiest database to get working
• Minimal data transformation between DB and server
• Company has dedicated “Developer Experience” team
*
Overview
•Part 1: Shopping Cart Application
• Search for products
• Add them to your cart
• Check out with Stripe
•Part 2: Using Node.js and 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
• MongoDB doesn’t have a JOIN equivalent
•But that’s what mongoose is for
• Mongoose provides pseudo-JOINs (separate queries)
*
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
Single thread - handler can’t be interrupted
Prints before
“done reading”
*
Why Async?
•Most web app/mobile app backends are I/O bound
• Multi-threading doesn’t help if CPU is just waiting for I/O
• Mostly just waiting for database to respond
•Nowadays there’s a REST API for everything
• Analytics and tracking: Segment
• Transactional email: Vero
• Mailing lists: MailChimp
•Threads are cumbersome for I/O bound programs
*
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!
TDD a REST API With Node.js and MongoDB

More Related Content

What's hot (20)

PPTX
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
PPTX
Getting Started with ASP.NET 5
Brij Mishra
 
PDF
ITT Flisol 2013
Domingo Suarez Torres
 
PDF
MEAN Stack - Google Developers Live 10/03/2013
Valeri Karpov
 
PDF
Hello world - intro to node js
Refresh Annapolis Valley
 
PPTX
[Blibli Brown Bag] Nodejs - The Other Side of Javascript
Irfan Maulana
 
PPTX
Testing your Single Page Application
Wekoslav Stefanovski
 
PPTX
Journey To The Front End World - Part3 - The Machine
Irfan Maulana
 
PPTX
Meanstack overview
Adthasid Sabmake
 
PDF
Isomorphic web application
Oliver N
 
PDF
The Dark Side of Single Page Applications
Dor Kalev
 
PDF
Node js projects
💾 Radek Fabisiak
 
PPTX
PHP Indonesia - Nodejs Web Development
Irfan Maulana
 
PPTX
MEAN Stack
RoshanTak1
 
PDF
The MEAN Stack
Md. Ziaul Haq
 
PDF
Afrimadoni the power of docker
PHP Indonesia
 
PPTX
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
Sencha
 
PPTX
Codegen2021 blazor mobile
Jose Javier Columbie
 
PPTX
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
MarkupBox
 
PDF
From MEAN to the MERN Stack
Troy Miles
 
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
Getting Started with ASP.NET 5
Brij Mishra
 
ITT Flisol 2013
Domingo Suarez Torres
 
MEAN Stack - Google Developers Live 10/03/2013
Valeri Karpov
 
Hello world - intro to node js
Refresh Annapolis Valley
 
[Blibli Brown Bag] Nodejs - The Other Side of Javascript
Irfan Maulana
 
Testing your Single Page Application
Wekoslav Stefanovski
 
Journey To The Front End World - Part3 - The Machine
Irfan Maulana
 
Meanstack overview
Adthasid Sabmake
 
Isomorphic web application
Oliver N
 
The Dark Side of Single Page Applications
Dor Kalev
 
Node js projects
💾 Radek Fabisiak
 
PHP Indonesia - Nodejs Web Development
Irfan Maulana
 
MEAN Stack
RoshanTak1
 
The MEAN Stack
Md. Ziaul Haq
 
Afrimadoni the power of docker
PHP Indonesia
 
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
Sencha
 
Codegen2021 blazor mobile
Jose Javier Columbie
 
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
MarkupBox
 
From MEAN to the MERN Stack
Troy Miles
 

Viewers also liked (20)

PDF
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
PPTX
Webinar: Get Started with the MEAN Stack
MongoDB
 
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
PPTX
Web Service Workshop - 3 days
David Ionut
 
PDF
JS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and Beyond
Valeri Karpov
 
PDF
MongoDB Miami Meetup 1/26/15: Introduction to WiredTiger
Valeri Karpov
 
PDF
JS-IL: Getting MEAN in 1 Hour
Valeri Karpov
 
PDF
Mongo db in 3 minutes BoilerMake
Valeri Karpov
 
PDF
MongoDB Israel June Meetup
Valeri Karpov
 
PDF
AngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous Integration
Valeri Karpov
 
PDF
MongoDB: Queries and Aggregation Framework with NBA Game Data
Valeri Karpov
 
PDF
NodeSummit - MEAN Stack
Valeri Karpov
 
PDF
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Valeri Karpov
 
PPTX
Postman Collection Format v2.0 (pre-draft)
Postman
 
PDF
Pentesting RESTful WebServices v1.0
n|u - The Open Security Community
 
PDF
Securty Testing For RESTful Applications
Source Conference
 
PDF
API Testing
Bikash Sharma
 
PPTX
Api testing
Keshav Kashyap
 
PPT
TestLink introduction
David Ionut
 
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
Webinar: Get Started with the MEAN Stack
MongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB
 
Web Service Workshop - 3 days
David Ionut
 
JS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and Beyond
Valeri Karpov
 
MongoDB Miami Meetup 1/26/15: Introduction to WiredTiger
Valeri Karpov
 
JS-IL: Getting MEAN in 1 Hour
Valeri Karpov
 
Mongo db in 3 minutes BoilerMake
Valeri Karpov
 
MongoDB Israel June Meetup
Valeri Karpov
 
AngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous Integration
Valeri Karpov
 
MongoDB: Queries and Aggregation Framework with NBA Game Data
Valeri Karpov
 
NodeSummit - MEAN Stack
Valeri Karpov
 
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Valeri Karpov
 
Postman Collection Format v2.0 (pre-draft)
Postman
 
Pentesting RESTful WebServices v1.0
n|u - The Open Security Community
 
Securty Testing For RESTful Applications
Source Conference
 
API Testing
Bikash Sharma
 
Api testing
Keshav Kashyap
 
TestLink introduction
David Ionut
 
Ad

Similar to TDD a REST API With Node.js and MongoDB (20)

PDF
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Mark Leusink
 
KEY
20120306 dublin js
Richard Rodger
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PDF
Cloud App Develop
Fin Chen
 
PPTX
Beginners Node.js
Khaled Mosharraf
 
PPTX
Mean stack
RavikantGautam8
 
PDF
MongoDB at Gilt Groupe
MongoDB
 
PDF
MongoDB
Serdar Buyuktemiz
 
PDF
An introduction to Node.js
Kasey McCurdy
 
PPTX
mearn-stackjdksjdsfjdkofkdokodkojdj.pptx
aravym456
 
PPTX
When to Use MongoDB
MongoDB
 
PDF
Mongodb at-gilt-groupe-seattle-2012-09-14-final
MongoDB
 
PDF
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
PDF
Mongo db first steps with csharp
Serdar Buyuktemiz
 
PPTX
Node js for enterprise
ravisankar munusamy
 
PDF
Surrogate dependencies (in node js) v1.0
Dinis Cruz
 
PPTX
What is Mean Stack Development ?
Balajihope
 
PPTX
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
PDF
Introduction to Node.js
Aaron Rosenberg
 
PPT
Mongo DB at Community Engine
Community Engine
 
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Mark Leusink
 
20120306 dublin js
Richard Rodger
 
NodeJS - Server Side JS
Ganesh Kondal
 
Cloud App Develop
Fin Chen
 
Beginners Node.js
Khaled Mosharraf
 
Mean stack
RavikantGautam8
 
MongoDB at Gilt Groupe
MongoDB
 
An introduction to Node.js
Kasey McCurdy
 
mearn-stackjdksjdsfjdkofkdokodkojdj.pptx
aravym456
 
When to Use MongoDB
MongoDB
 
Mongodb at-gilt-groupe-seattle-2012-09-14-final
MongoDB
 
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Mongo db first steps with csharp
Serdar Buyuktemiz
 
Node js for enterprise
ravisankar munusamy
 
Surrogate dependencies (in node js) v1.0
Dinis Cruz
 
What is Mean Stack Development ?
Balajihope
 
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
Introduction to Node.js
Aaron Rosenberg
 
Mongo DB at Community Engine
Community Engine
 
Ad

More from Valeri Karpov (9)

PDF
A Practical Introduction to GeoJSON
Valeri Karpov
 
PDF
A Practical Introduction to Functions-as-a-Service
Valeri Karpov
 
PDF
A Gentle Introduction to Functions-as-a-Service
Valeri Karpov
 
PDF
Introducing Async/Await
Valeri Karpov
 
PDF
TAO and the Essence of Modern JavaScript
Valeri Karpov
 
PDF
Mastering Async/Await in JavaScript
Valeri Karpov
 
PDF
React, Redux, and Archetype
Valeri Karpov
 
PDF
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
Valeri Karpov
 
PDF
MongoDB API Talk @ HackPrinceton
Valeri Karpov
 
A Practical Introduction to GeoJSON
Valeri Karpov
 
A Practical Introduction to Functions-as-a-Service
Valeri Karpov
 
A Gentle Introduction to Functions-as-a-Service
Valeri Karpov
 
Introducing Async/Await
Valeri Karpov
 
TAO and the Essence of Modern JavaScript
Valeri Karpov
 
Mastering Async/Await in JavaScript
Valeri Karpov
 
React, Redux, and Archetype
Valeri Karpov
 
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
Valeri Karpov
 
MongoDB API Talk @ HackPrinceton
Valeri Karpov
 

Recently uploaded (20)

PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 

TDD a REST API With Node.js and MongoDB

  • 1. Developing and Testing a MongoDB and Node.js REST API Valeri Karpov Node.js Engineer, MongoDB www.thecodebarbarian.com github.com/vkarpov15 @code_barbarian
  • 2. * What is this talk about? •Briefly introduce MongoDB and Node.js •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 •Upcoming EdX course
  • 3. * What is MongoDB? •Document database - store objects, not columns •Often better* performance • Better data locality than RDBMS for 1 query vs 5 JOINs
  • 4. * What is MongoDB? •Easier ops • No need to set up databases, tables, schemas, etc. • Run one executable, you now have a working db • MongoDB Cloud Manager and Ops Manager •Developer sanity • In my experience, easiest database to get working • Minimal data transformation between DB and server • Company has dedicated “Developer Experience” team
  • 5. * Overview •Part 1: Shopping Cart Application • Search for products • Add them to your cart • Check out with Stripe •Part 2: Using Node.js and the Mongoose ODM •Part 3: Schema Design •Part 4: Building an API with the Express framework •Part 5: Testing with Mocha + Superagent
  • 6. * Part 1: What Does the App Do?
  • 7. * What Does the App Do?
  • 8. * What Does the App Do?
  • 9. * 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
  • 10. * Schema Relationships •Product belongs to one or more categories •Users can have multiple products in their cart •Representing relationships in MongoDB is tricky • MongoDB doesn’t have a JOIN equivalent •But that’s what mongoose is for • Mongoose provides pseudo-JOINs (separate queries)
  • 11. * 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.
  • 12. * Brief Overview of Node.js •require() ● Async I/O
  • 13. * 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 Single thread - handler can’t be interrupted Prints before “done reading”
  • 14. * Why Async? •Most web app/mobile app backends are I/O bound • Multi-threading doesn’t help if CPU is just waiting for I/O • Mostly just waiting for database to respond •Nowadays there’s a REST API for everything • Analytics and tracking: Segment • Transactional email: Vero • Mailing lists: MailChimp •Threads are cumbersome for I/O bound programs
  • 16. * Using Your Schema Create User Save user to MongoDB Load user from MongoDB Print user to stdout
  • 17. * Part 2 Takeaways •Mongoose provides several neat features • Model part of MVC • Default values • Schema validation and declarative schema design
  • 18. * Part 3: Schema Design •3 schemas: • Product • Category • User •Going to use mongoose to define schemas •Will use a couple key schema design principles
  • 22. * Category Schema Queries •What categories are descendants of “Electronics”? • • •What categories are children of “Non-Fiction”? • •What categories are ancestors of “Phones”?
  • 24. * 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
  • 25. * User Schema User’s cart as an array of ObjectIds...
  • 26. * 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
  • 27. * Part 4: The Express Framework •Most popular Node.js web framework •Simple, pluggable, and fast •Great tool for building REST APIs
  • 28. * Your First Express App Route Parameter
  • 29. * What is REST? •Representational State Transfer •HTTP request -> JSON HTTP response •Business logic on top of MongoDB schemas • Access control, emails, analytics, etc.
  • 34. * Adding Products to User’s Cart •Recall cart is an array of products
  • 35. * Adding Products to User’s Cart Get cart from HTTP request Overwrite user’s cart Let mongoose handle casting and validating data
  • 36. * PUT /me/cart Takeaways •Mongoose lets you be lazy •Access control using subdocs
  • 37. * Bonus: Stripe Checkout Create a Stripe charge with the npm ‘stripe’ module
  • 38. * Bonus: Stripe Checkout Error handling Empty user cart on success
  • 39. * 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
  • 40. * Part 5: Test-Driven Development •Building an API is tricky •Lots of different error conditions •Express has a lot of magic under the hood
  • 41. * 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
  • 42. * Superagent •NodeJS HTTP client •Isomorphic: runs in both browser and NodeJS •Same author as Express
  • 43. * Mocha •Testing Framework for NodeJS •Same author as Express •BDD-style syntax • describe() -> test suite • it() -> individual test
  • 46. * 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
  • 47. * •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!