SlideShare a Scribd company logo
1 of 73
Download to read offline
1 Hour MEAN Stack Hackathon
Valeri Karpov
Software Engineer, MongoDB
www.thecodebarbarian.com
www.slideshare.net/vkarpov15
github.com/vkarpov15
@code_barbarian
Building a Food Journal Single Page App + Workflow
*
Who is this guy?
•Coined the MEAN stack in April ‘13
•Contributor to:
• node-mongodb-native
• mongoose
• mquery
• omni-di, etc.
•AngularJS since 0.9.4 in 2010
•Production MEAN apps: Ascot Project, Bookalokal
*
General Outline
•Building a single page app - LeanMEAN
•Food journal counts calories for you (FitDay)
•MEAN = MongoDB, ExpressJS, AngularJS, NodeJS
•Additional tools:
• browserify
• make
• omni-di
• mongoose
• MongoDB 2.6 text search
• PassportJS / Twitter oauth
*
What we’re building
*
Beyond the Hack
•Nitty-gritty deep dive into code and workflow
•Build tools and workflow: browserify, make
•Code organization: browserify, omni-di
•Unit testing and benchmarks: mocha
*
Step by Step
•Step 0: Understand SR-25 data set
•Step 1: Create Express app
•Step 2: Restructure Express app
•Step 3: Construct Models
•Step 4: Define API
•Step 5: Set up client-side routing
•Step 6: Client-side integration with API
*
Step by Step, Continued
•Step 7: Unit testing
•Step 8: Authentication
*
Follow along on GitHub
*
Step 0: USDA SR-25 Nutrition Data
•Need data: calories, carbs, lipids for common foods
•Thankfully available from USDA’s website
•mongorestore-friendly dump for MongoDB here
•My blog post about the data set
*
What does SR-25 data look like?
*
What Nutrients Look Like
*
What Weights Look Like
*
Simple SR-25 Query
•How many carbs in 1 serving of raw kale?
•Good baby step for food journal
*
Text Search in MongoDB 2.6
•Don’t want users to have to enter “Kale, raw”
•Example: top 3 results for “grass-fed beef”
*
Text Search in MongoDB 2.6
•Static data = perfect use case for text search
•Need to create a text index first from shell:
• db.nutrition.ensureIndex({ description :
“text” });
•Read more here
*
Step 1: Creating an Express App
•Can create an Express app with 2 commands:
• `npm install express -g` installs Express
• `express lean-mean-nutrition-sample` creates the
app
*
Step 2: Restructuring the App
•Single page app doesn’t need Jade templating
•views folder obsolete
•Set up package.json file
•package.json - workflow for setting up env:
• `git clone`: pull down repo
• `npm install`: install dependencies
• `npm test`: run tests
• `npm start`: start the server
*
passport.json Setup
*
Step 3: Create Database Schema
“Ontology deals with questions concerning what entities
exist or can be said to exist, and how such entities can
be grouped, related within a hierarchy, and subdivided
according to similarities and differences”
- Wikipedia article on ontology
*
Quick Overview of Mongoose
•ODM for MongoDB and NodeJS
•Schema design and validation
•Convenience objects
•MEAN Stack’s official best friend
*
Objects in LeanMEAN World
•FoodItem: from SR-25
•User: because any real API scopes by user
•Day: the FoodItems a User ate on a given date
*
First, SR-25 Nutrition Item Schema
*
Having Users is a Positive
*
Constructing the Day Schema
*
Day Schema Subtleties
•Want to let user select from multiple weights
•Want user to enter custom amount for a weight
•Difference between selectedWeight / weights
•Nutrient amounts per 100G
*
Omni-di to tie this all together
•Avoid dependency hell: don’t require in every file!
*
Omni-di’s `assemble()` function
*
Why Two Food Item Services?
Text score sorting in Mongoose, see pull request
Will be fixed in next version of Mongoose!
*
Step 4: Define an API
Complexity creeps up on you like a snake in the grass.
Good thing we have a Mongoose on our side!
*
The API Methods
*
Search for a Food Item
Note: text search API is atypical, docs here
*
Load a Day
*
Save a Day
*
Wait, Where’s The Work?
•Mongoose validates client foods data w/ schema
•Only modifying foods - free access control
•No need to check if date exists: upsert flag
•isNew flag in `GET /api/date/:date`
*
Step 5: AngularJS + Browserify
•Single Page App: how to manage code bloat?
*
Browserify = Write Node For Client
•AngularJS dependency in package.json
•Never deal with flakey CDNs again!
*
Build Process with Browserify
•Output: all.js, contains all JS in 1 file
•Input: all files in client directory + dependencies
•browserify -o ./public/javascripts/all.js
client/*
•Or, make build_client
*
Single Page App Basics
*
What index.html Looks Like
ng-view is where the magic happens
*
http://localhost:3000/#/
*
http://localhost:3000/#/track
*
Why Single Page App?
•No server side templating:
• Better server throughput
• Cleaner separation of concerns
• Less bandwidth usage
•More control over UX
*
Step 6: Let’s Build a Client!
•AngularJS controller for each particular view
•Right now only need TrackController
•Controller talks to server
•Controller provides API for UI
*
Modifying the AngularJS Module
*
TrackController Structure
*
TrackController API
*
TrackController in the HTML
*
Implementation of loadDay()
*
Implementation of recalculate() ?
*
Code Sharing - calculations.js
*
NodeJS SPA and Code Sharing
•Code sharing is trivial with browserify
•MEAN stack principle: The objects your server deals
with should be almost identical to the objects your client
deals with and the objects stored in your database.
•Same objects => easy code sharing
•Calculations a good candidate in this case
*
search() call
*
addFood() call
*
Step 7: Unit Testing with Kittens
*
Get Serious About Testing
•Foundation: proper unit tests, automation
•Heuristic: code “works” iff npm test succeeds
•Grunt or Makefile, either works well
*
Omni-di and unit tests
•Beauty of DI: easy to control how much to stub
•For unit tests, stub everything
*
Testing PUT /api/day/:date
*
Testing PUT /api/day/:date
*
Testing TrackController
*
Testing TrackController
*
Tying Tests Together with make
*
Browserify SPA Testing Advantages
•Code sharing
•Single test framework - Mocha
*
Step 8: Authentication
•Last step!
*
Authentication in SPA
•PassportJS makes oauth easy
•But… requires redirect
•Not that much of a problem
•Handle cases where user hits API but not logged in
*
Setting up app.js with Passport
*
checkLogin middleware
*
checkLogin and TrackController
*
Passport Setup
*
Client-side User Tracking
*
Displaying the Logged In User
*
Displaying the Logged In User
*
And that’s a wrap! Time to Review
•Single page app with MEAN stack
•AngularJS routing
•Browserify for building client code
•Validating complex objects with Mongoose
•MongoDB text search
•Testing and automation
•Twitter Oauth
*
Thanks for Listening!
•Slides on:
• Twitter: @code_barbarian
• Slideshare: slideshare.net/vkarpov15
•Repo on github: github.com/vkarpov15/lean-mean-
nutrition-sample
•Blog post on SR-25 data set

More Related Content

What's hot

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
Rob Davarnia
 

What's hot (19)

Afrimadoni the power of docker
Afrimadoni   the power of dockerAfrimadoni   the power of docker
Afrimadoni the power of docker
 
Isomorphic React Applications: Performance And Scalability
Isomorphic React Applications: Performance And ScalabilityIsomorphic React Applications: Performance And Scalability
Isomorphic React Applications: Performance And Scalability
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN Stack
 
Getting Started With WP REST API
Getting Started With WP REST APIGetting Started With WP REST API
Getting Started With WP REST API
 
Real time web
Real time webReal time web
Real time web
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
React server side rendering performance
React server side rendering performanceReact server side rendering performance
React server side rendering performance
 
The MEAN Stack
The MEAN StackThe MEAN Stack
The MEAN Stack
 
The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseGrokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with Couchbase
 
The busy developers guide to Docker
The busy developers guide to DockerThe busy developers guide to Docker
The busy developers guide to Docker
 
MEAN Stack
MEAN StackMEAN Stack
MEAN Stack
 
Performance and Scalability Art of Isomorphic React Applications
Performance and Scalability Art of Isomorphic React ApplicationsPerformance and Scalability Art of Isomorphic React Applications
Performance and Scalability Art of Isomorphic React Applications
 
Mean Stack - An Overview
Mean Stack - An OverviewMean Stack - An Overview
Mean Stack - An Overview
 
Tooling for the productive front-end developer
Tooling for the productive front-end developerTooling for the productive front-end developer
Tooling for the productive front-end developer
 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescue
 
MEAN Stack - Google Developers Live 10/03/2013
MEAN Stack - Google Developers Live 10/03/2013MEAN Stack - Google Developers Live 10/03/2013
MEAN Stack - Google Developers Live 10/03/2013
 
Before start
Before startBefore start
Before start
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI AutomationMaking Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI Automation
 

Viewers also liked (8)

Mongo db in 3 minutes BoilerMake
Mongo db in 3 minutes   BoilerMakeMongo db in 3 minutes   BoilerMake
Mongo db in 3 minutes BoilerMake
 
MongoDB Israel June Meetup
MongoDB Israel June MeetupMongoDB Israel June Meetup
MongoDB Israel June Meetup
 
MongoDB Miami Meetup 1/26/15: Introduction to WiredTiger
MongoDB Miami Meetup 1/26/15: Introduction to WiredTigerMongoDB Miami Meetup 1/26/15: Introduction to WiredTiger
MongoDB Miami Meetup 1/26/15: Introduction to WiredTiger
 
AngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous Integration
AngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous IntegrationAngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous Integration
AngularJS Meetup 11/19/13 - AngularJS for MongoDB Continuous Integration
 
JS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and Beyond
JS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and BeyondJS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and Beyond
JS-IL Keynote: MongoDB 2.6, Mongoose 4.0, and Beyond
 
MongoDB: Queries and Aggregation Framework with NBA Game Data
MongoDB: Queries and Aggregation Framework with NBA Game DataMongoDB: Queries and Aggregation Framework with NBA Game Data
MongoDB: Queries and Aggregation Framework with NBA Game Data
 
NodeSummit - MEAN Stack
NodeSummit - MEAN StackNodeSummit - MEAN Stack
NodeSummit - MEAN Stack
 
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
 

Similar to MEAN Stack Workshop at Node Philly, 4/9/14

MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt Groupe
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
MongoDB
 
Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014
Damian Beresford
 

Similar to MEAN Stack Workshop at Node Philly, 4/9/14 (20)

Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST API
 
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
 
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
 
MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt Groupe
 
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
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
 
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN StackMongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
 
Testing with Codeception
Testing with CodeceptionTesting with Codeception
Testing with Codeception
 
AngularJS One Day Workshop
AngularJS One Day WorkshopAngularJS One Day Workshop
AngularJS One Day Workshop
 
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
 
Migrating from MongoDB to Neo4j - Lessons Learned
Migrating from MongoDB to Neo4j - Lessons LearnedMigrating from MongoDB to Neo4j - Lessons Learned
Migrating from MongoDB to Neo4j - Lessons Learned
 
Xamarin.Forms Bootcamp
Xamarin.Forms BootcampXamarin.Forms Bootcamp
Xamarin.Forms Bootcamp
 
Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014Node.js Dublin Meetup April 2014
Node.js Dublin Meetup April 2014
 
Untangling spring week11
Untangling spring week11Untangling spring week11
Untangling spring week11
 
Front-End Tools and Workflows
Front-End Tools and WorkflowsFront-End Tools and Workflows
Front-End Tools and Workflows
 
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
 
Building JavaScript
Building JavaScriptBuilding JavaScript
Building JavaScript
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
 
Rapid Application Development on Google App Engine for Java
Rapid Application Development on Google App Engine for JavaRapid Application Development on Google App Engine for Java
Rapid Application Development on Google App Engine for Java
 

More from Valeri Karpov

More from Valeri Karpov (9)

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

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

MEAN Stack Workshop at Node Philly, 4/9/14