SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
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!
Developing and Testing a MongoDB and Node.js REST API

Más contenido relacionado

La actualidad más candente

Building Micro-Services with Scala
Building Micro-Services with ScalaBuilding Micro-Services with Scala
Building Micro-Services with ScalaYardena Meymann
 
MJ Berends talk - Women & Non-Binary Focused Intro to AWS
 MJ Berends talk - Women & Non-Binary Focused Intro to AWS MJ Berends talk - Women & Non-Binary Focused Intro to AWS
MJ Berends talk - Women & Non-Binary Focused Intro to AWSAWS Chicago
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Ryan Cuprak
 
Start with Angular framework
Start with Angular frameworkStart with Angular framework
Start with Angular frameworkKnoldus Inc.
 
CFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful CodeCFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful Codeindiver
 
Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Alex Thissen
 
Scaling tokopedia-past-present-future
Scaling tokopedia-past-present-futureScaling tokopedia-past-present-future
Scaling tokopedia-past-present-futureRein Mahatma
 
Container Orchestration for .NET Developers
Container Orchestration for .NET DevelopersContainer Orchestration for .NET Developers
Container Orchestration for .NET DevelopersMike Melusky
 
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens  SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens Sencha
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
A brief intro to nodejs
A brief intro to nodejsA brief intro to nodejs
A brief intro to nodejsJay Liu
 
Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014Damian Beresford
 
Engage 2019: The good, the bad and the ugly: a not so objective view on front...
Engage 2019: The good, the bad and the ugly: a not so objective view on front...Engage 2019: The good, the bad and the ugly: a not so objective view on front...
Engage 2019: The good, the bad and the ugly: a not so objective view on front...Frank van der Linden
 
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Codemotion
 
Andrea Di Persio
Andrea Di PersioAndrea Di Persio
Andrea Di PersioCodeFest
 

La actualidad más candente (20)

Building Micro-Services with Scala
Building Micro-Services with ScalaBuilding Micro-Services with Scala
Building Micro-Services with Scala
 
MJ Berends talk - Women & Non-Binary Focused Intro to AWS
 MJ Berends talk - Women & Non-Binary Focused Intro to AWS MJ Berends talk - Women & Non-Binary Focused Intro to AWS
MJ Berends talk - Women & Non-Binary Focused Intro to AWS
 
Hello world - intro to node js
Hello world - intro to node jsHello world - intro to node js
Hello world - intro to node js
 
Node.js Chapter1
Node.js Chapter1Node.js Chapter1
Node.js Chapter1
 
Mini-Training: Redis
Mini-Training: RedisMini-Training: Redis
Mini-Training: Redis
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Start with Angular framework
Start with Angular frameworkStart with Angular framework
Start with Angular framework
 
CFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful CodeCFWheels - Pragmatic, Beautiful Code
CFWheels - Pragmatic, Beautiful Code
 
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
 
Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!Run your Dockerized ASP.NET application on Windows and Linux!
Run your Dockerized ASP.NET application on Windows and Linux!
 
Scaling tokopedia-past-present-future
Scaling tokopedia-past-present-futureScaling tokopedia-past-present-future
Scaling tokopedia-past-present-future
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Container Orchestration for .NET Developers
Container Orchestration for .NET DevelopersContainer Orchestration for .NET Developers
Container Orchestration for .NET Developers
 
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens  SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
SenchaCon 2016: Being Productive with the New Sencha Fiddle - Mitchell Simoens
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
A brief intro to nodejs
A brief intro to nodejsA brief intro to nodejs
A brief intro to nodejs
 
Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014
 
Engage 2019: The good, the bad and the ugly: a not so objective view on front...
Engage 2019: The good, the bad and the ugly: a not so objective view on front...Engage 2019: The good, the bad and the ugly: a not so objective view on front...
Engage 2019: The good, the bad and the ugly: a not so objective view on front...
 
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
 
Andrea Di Persio
Andrea Di PersioAndrea Di Persio
Andrea Di Persio
 

Destacado

TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBValeri Karpov
 
Mongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsMongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsYuriy Bogomolov
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB AppHenrik Ingo
 
Kalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB TutorialsKalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB TutorialsKalp Corporate
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise developmentPavel Tiunov
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Dmytro Mindra
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCPavel Tiunov
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack FrameworkMarudi Subakti
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS Pavel Tsukanov
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...GeeksLab Odessa
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.jsTimur Shemsedinov
 
Super powered API testing
Super powered API testing Super powered API testing
Super powered API testing postmanclient
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsGeeksLab Odessa
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
SOAP-UI The Web service Testing
SOAP-UI The Web service TestingSOAP-UI The Web service Testing
SOAP-UI The Web service TestingGanesh Mandala
 
4 Major Advantages of API Testing
4 Major Advantages of API Testing4 Major Advantages of API Testing
4 Major Advantages of API TestingQASource
 

Destacado (20)

TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDB
 
Mongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsMongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.js
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 
Kalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB TutorialsKalp Corporate MongoDB Tutorials
Kalp Corporate MongoDB Tutorials
 
Node.js (RichClient)
 Node.js (RichClient) Node.js (RichClient)
Node.js (RichClient)
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise development
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POC
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack Framework
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.js
 
Super powered API testing
Super powered API testing Super powered API testing
Super powered API testing
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.js
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
SOAP-UI The Web service Testing
SOAP-UI The Web service TestingSOAP-UI The Web service Testing
SOAP-UI The Web service Testing
 
Api testing
Api testingApi testing
Api testing
 
4 Major Advantages of API Testing
4 Major Advantages of API Testing4 Major Advantages of API Testing
4 Major Advantages of API Testing
 

Similar a Developing and Testing a MongoDB and Node.js REST API

Webinar: Get Started with the MEAN Stack
Webinar: Get Started with the MEAN StackWebinar: Get Started with the MEAN Stack
Webinar: Get Started with the MEAN StackMongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovDevelop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovMongoDB
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovDevelop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovMongoDB
 
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Escaping the yellow bubble - rewriting Domino using MongoDb and AngularEscaping the yellow bubble - rewriting Domino using MongoDb and Angular
Escaping the yellow bubble - rewriting Domino using MongoDb and AngularMark Leusink
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Cloud App Develop
Cloud App DevelopCloud App Develop
Cloud App DevelopFin Chen
 
MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.jsKasey McCurdy
 
JS-IL: Getting MEAN in 1 Hour
JS-IL: Getting MEAN in 1 HourJS-IL: Getting MEAN in 1 Hour
JS-IL: Getting MEAN in 1 HourValeri Karpov
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDBMongoDB
 
Mongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-finalMongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-finalMongoDB
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Mongo db first steps with csharp
Mongo db first steps with csharpMongo db first steps with csharp
Mongo db first steps with csharpSerdar Buyuktemiz
 
Surrogate dependencies (in node js) v1.0
Surrogate dependencies  (in node js)  v1.0Surrogate dependencies  (in node js)  v1.0
Surrogate dependencies (in node js) v1.0Dinis Cruz
 

Similar a Developing and Testing a MongoDB and Node.js REST API (20)

Webinar: Get Started with the MEAN Stack
Webinar: Get Started with the MEAN StackWebinar: Get Started with the MEAN Stack
Webinar: Get Started with the MEAN Stack
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovDevelop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val Karpov
 
Develop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val KarpovDevelop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val Karpov
 
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
Escaping the yellow bubble - rewriting Domino using MongoDb and AngularEscaping the yellow bubble - rewriting Domino using MongoDb and Angular
Escaping the yellow bubble - rewriting Domino using MongoDb and Angular
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Cloud App Develop
Cloud App DevelopCloud App Develop
Cloud App Develop
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Meanstack overview
Meanstack overviewMeanstack overview
Meanstack overview
 
Mean stack
Mean stackMean stack
Mean stack
 
MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt Groupe
 
MongoDB
MongoDBMongoDB
MongoDB
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
 
JS-IL: Getting MEAN in 1 Hour
JS-IL: Getting MEAN in 1 HourJS-IL: Getting MEAN in 1 Hour
JS-IL: Getting MEAN in 1 Hour
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDB
 
Mongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-finalMongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-final
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Mongo db first steps with csharp
Mongo db first steps with csharpMongo db first steps with csharp
Mongo db first steps with csharp
 
Node js for enterprise
Node js for enterpriseNode js for enterprise
Node js for enterprise
 
Surrogate dependencies (in node js) v1.0
Surrogate dependencies  (in node js)  v1.0Surrogate dependencies  (in node js)  v1.0
Surrogate dependencies (in node js) v1.0
 

Más de All Things Open

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityAll Things Open
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best PracticesAll Things Open
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public PolicyAll Things Open
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...All Things Open
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashAll Things Open
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptAll Things Open
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?All Things Open
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractAll Things Open
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlowAll Things Open
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and SuccessAll Things Open
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with BackgroundAll Things Open
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblyAll Things Open
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksAll Things Open
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptAll Things Open
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramAll Things Open
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceAll Things Open
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamAll Things Open
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in controlAll Things Open
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsAll Things Open
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...All Things Open
 

Más de All Things Open (20)

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of Observability
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best Practices
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public Policy
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil Nash
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScript
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart Contract
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and Success
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with Background
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssembly
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in Haystacks
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit Intercept
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship Program
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open Source
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache Beam
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in control
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
 

Último

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Developing and Testing a MongoDB and Node.js REST API

  • 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
  • 15. * Your First Mongoose Schema matches X@Y.Z
  • 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!