mongodb days silicon valley: building applications with the mean stack

39
MEAN Stack Introduction and Development Jason Zucchetto MongoDB

Upload: mongodb

Post on 14-Apr-2017

1.041 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

MEAN Stack Introduction and Development

Jason ZucchettoMongoDB

Page 2: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

2

Agenda

• Developing a Sample Application• The MEAN Stack Components• MEAN Stack Components Explained for Our

Sample Application

Page 3: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

3

MongoMart

• Simple application for searching and viewing MongoDB swag

• All product information stored in MongoDB• Github location for the sample application will

be shown at the end of this presentation

Page 4: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

4

MongoMart

Page 5: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

5

MongoMart

Page 6: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

6

MEAN Stack Components

Page 7: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

7

MongoDB

• Document Oriented Database (JSON document)• Returns JSON results, making it very easy to

store and retrieve JSON documents from your Node.js application

• Dynamic schema• Advanced secondary indexes (similar to an

RDBMS)• Replication and scaling

Page 8: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

8

Express

• Most popular Node.js web framework• Simple, pluggable, and fast• Great tool for building REST APIs• Allows us to easily create endpoints in our

application (e.g. /items/45)

Page 9: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

9

Angular

• Javascript framework for client side MVC (model-view-controller)

• Create single page webapps• HTML is used as the template language• Adds HTML elements/attributes and

interprets those elements/attributes• Frontend of the MEAN stack

Page 10: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

10

Node.js

• Our web server• Used for server-side web applications• “… event-driven architecture and a non-

blocking I/O API designed to optimize an application's throughput and scalability for real-time web applications”

Page 11: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

11

Setting Up MongoDB for our MongoMart App

• Download MongoDB• Extract and add /bin directory to system

PATH• Create data directory• Start MongoDB and point to data directory• Load dataset using mongoimport

(instructions in GitHub, link at the end of this presentation)

Page 12: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

{"_id" : 20,"title" : "MongoDB University T-shirt","slogan" : "Show Your MDBU Alumni Status","description" : "Crafted from ultra-soft combed

cotton, this essential t-shirt features sporty contrast tipping and MongoDB's signature leaf.",

"stars" : 0,"category" : "Apparel","img_url" : "/img/products/univ-tshirt.jpg","price" : 45

}

Document from “items” Collection

Page 13: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

13

Querying “items” Collection

• Any field within the collection can be queried, e.g. db.items.find( { “category” : “Apparel” } )

• Ideally, every query to the database uses an index, to ensure we maintain fast performance as the database grows in size

Page 14: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

Using .explain() in the MongoDB Shell

> db.items.find({ "category" : "Apparel" } ).explain("executionStats"){

…"executionStats" : {

"executionSuccess" : true,"nReturned" : 6,"executionTimeMillis" : 2,"totalKeysExamined" : 6,"totalDocsExamined" : 6,"executionStages" : {

"stage" : "FETCH",…

}…

Page 15: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

15

Item Reviews

• Several options• Add a list of reviews to each “items”

document• Create a new collection called “reviews”,

query the collection for latest reviews for an item

• Create a collection called “reviews” and maintain the last 10 reviews (or 10 most popular reviews) in each “items” document (duplicating reviews across the two collections)

Page 16: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

16

Node.js

• Our webserver• Easily clone the MongoMart github repo,

install needed dependencies, and run the server:git clone <REPO>npm installnpm start

Page 17: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

17

What is NPM

● Bundled in the Node.js installer● Dependency and management tool for

Node.js● Used for installing Node.js modules, such

as Express (which we’ll dive into next):npm install express

Page 18: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

18

Integrating Express Into MongoMart

● Express is a Node.js module to manage our routes

● Initially, Express was installed, and the Express generator for generating the complete structure for an application

● Use the Express generator to generate the MongoMart application

npm install expressnpm install express-generator -g

express mongomart

Page 19: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

19

Routes Generated By Express// Within routes/users.js

var express = require('express');var router = express.Router();

/* GET users listing. */router.get('/', function(req, res, next) { res.send('respond with a resource');});

module.exports = router;

Page 20: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

20

Create New Routes for MongoMart Items// Create new file routes/items.jsvar express = require('express');var router = express.Router();

/* GET all items */router.get('/', function(req, res, next) { // Query MongoDB for items});

/* GET item by id */router.get('/:id', function(req, res, next) { // Query MongoDB for an item});

module.exports = router;

Page 21: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

21

● MongoDB running with sample data● Node.js application created● Express installed for managing routes

(e.g. /items) within our Node.js application

Recap MongoMart Progress

● Query MongoDB from our application’s routes

● Display items to the user via Angular

Next Steps

Page 22: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

22

● ODM for writing MongoDB validation, casting, and business logic

● Greater simplifies how we query and work with MongoDB

Adding Mongoose to Our Application

npm install mongoose

Page 23: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

23

Create a Model for a MongoMart Item// In models/item.js

var mongoose = require("mongoose");var ItemSchema = new mongoose.Schema({ _id: Number, name: String, title: String, slogan: String, description: String, stars: Number, category: { type: String, index: true }, img_url: String, price: Number});

module.exports = mongoose.model('Item', ItemSchema);

Page 24: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

24

Mongoose MongoDB query from our Node.js App// In routes/items.js

var mongoose = require( 'mongoose' );var Item = require(__dirname+'/../models/Item')

/* GET all items */router.get('/', function(req, res, next) { Item.find(function(err, items) { if (err) res.send(err);

res.json(items); });});

Page 25: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

25

Mongoose MongoDB query from our Node.js App

// In routes/items.js

* GET item by id */router.get('/:id', function(req, res, next) { Item.findById({ "_id" : req.params.id }, function(err, item) { if (err) res.send(err);

res.json(item); });});

Page 26: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

26

● Angular is a Javascript framework ● Client side MVC● Create single page webapps, define all views

and controllers in client side Javascript● Since Angular is a client side framework, we’ll

install via bower● Bower should be used for client side

components (bootstrap, Angular, etc.)● npm for node.js dependencies (Express,

Mongoose, etc.)

Integrating Angular Into MongoMart

Page 27: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

27

Integrating Angular Into MongoMart

bower install bootstrap // used for easy layouts/standard stylesbower install angular // the main angular.js filebower install angular-route // needed for routing in angularbower install angular-animate // animate transitions between viewsbower install jquery // jquery library

ls bower_components/Angular angular-animate angular-route bootstrap jquery

Page 28: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

28

Integrating Angular Into MongoMart (index)<!doctype html><html lang="en" ng-app="mongomartApp">

<head> <meta charset="utf-8"> <title>MongoMart</title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="stylesheets/style.css"> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <script src="bower_components/angular-animate/angular-animate.js"></script> <script src="javascripts/app.js"></script> <script src="javascripts/controllers.js"></script></head><body>

<div class="view-container"><div ng-view class="view-frame"></div></div></body>

</html>

Page 29: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

29

Integrating Angular Into MongoMart (app.js)var mongomartApp = angular.module('mongomartApp', ['ngRoute','mongomartControllers','ngAnimate']);

mongomartApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/items', { templateUrl: 'partials/item-list.html', controller: 'ItemListCtrl' }). when('/items/:itemId', { templateUrl: 'partials/item-detail.html', controller: 'ItemDetailCtrl' }). otherwise({ redirectTo: '/items' }); }]);

Page 30: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

30

Integrating Angular Into MongoMart (app.js)

Page 31: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

31

Integrating Angular Into MongoMart (controllers.js)

var mongomartControllers = angular.module('mongomartControllers', []);

mongomartControllers.controller('ItemListCtrl', ['$scope', '$http', function($scope, $http) { $http.get('http://localhost:3000/items').success(function(data) { $scope.items = data; });

$scope.itemOrder = 'title'; }]);

mongomartControllers.controller('ItemDetailCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { $scope.itemId = $routeParams.itemId;

$http.get('http://localhost:3000/items/' + $routeParams.itemId).success(function(data) { $scope.item = data; }); }]);

Page 32: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

32

Integrating Angular Into MongoMart (item-detail.html)

<div class="row"> <div class="col-md-8"> <img class="img-responsive" src="{{item.img_url}}" alt=""> </div>

<div class="col-md-4"> <h3>Product Description</h3> <p> {{item.description}} </p> </div></div>

Page 33: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

33

● MongoDB as the backing database ● Express for routing in Node.js (e.g. /items)● Angular for client side MVC, single page webapp● Node.js as our application server

MEAN Stack for MongoMart

Page 34: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

Our Node.js Application StructureClient side components, such as Javascript libraries and CSS (e.g. Bootstrap). Brief intro to Bower in the Angular section of this presentation.

Our models using Mongoose

Publicly accessible static files, such as images and CSS.

Routes defined by express.

Templates populated by routes from above

app.js is our application’s starting place, this file is used to load all dependencies and other Node.js files

Page 35: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

35

MongoMart

Page 36: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

36

MongoMart

Page 37: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

37

Links

• MongoMart Github Location: https://github.com/zuketo/meanstack

• MEAN Stack Course on Edx: https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x

Page 38: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

#MDBDaysmongodb.com

Get your technical questions answered

In the foyer, 10:00 - 5:00By appointment only – register in person

Page 39: MongoDB Days Silicon Valley: Building Applications with the MEAN Stack

Tell me how I did today on Guidebook and enter for a chance to win one of these

How to do it: Download the Guidebook App

Search for MongoDB Silicon Valley Submit session feedback