node-il meetup 12/2

51
Getting Started With MongoDB and Mongoose { author: “Ynon Perek” } Tuesday, February 12, 13

Upload: ynon-perek

Post on 17-May-2015

700 views

Category:

Technology


0 download

DESCRIPTION

Getting Started With Node.JS and Mongoose talk for the Node.JS-IL meetup.

TRANSCRIPT

Page 1: Node-IL Meetup 12/2

Getting Started With MongoDB and Mongoose{ author: “Ynon Perek” }

Tuesday, February 12, 13

Page 2: Node-IL Meetup 12/2

Whoami

Ynon Perek

http://ynonperek.com

[email protected]

Tuesday, February 12, 13

Page 3: Node-IL Meetup 12/2

Agenda

Mongo Is Awesome

CRUD Operations

Mongoose

Coding Time

Tuesday, February 12, 13

Page 4: Node-IL Meetup 12/2

Part of the NoSQL Family

COUCH DB CASSANDRA

REDIS

FLOCKDB

SIMPLEDB

Tuesday, February 12, 13

Page 5: Node-IL Meetup 12/2

But Most Popular Of All

Tuesday, February 12, 13

Page 6: Node-IL Meetup 12/2

Mongo Is Awesome

Data Store for JSON Objects

Tuesday, February 12, 13

Page 7: Node-IL Meetup 12/2

Mongo Is Awesome

Data Store for JSON Objects

{ “Name” : “Rose Tyler” }

Tuesday, February 12, 13

Page 8: Node-IL Meetup 12/2

JSON Objects

A JSON Object is a collection of key/value pairs

Keys are simple strings

Values can be: Numbers, Strings, Arrays, Other Objects, and more

{  "name" : "Rose Tyler",  "race" : "Human",  "body parts" : [ "head", "legs"]}

Tuesday, February 12, 13

Page 9: Node-IL Meetup 12/2

Mongo saves the data in a binary format called BSON

Spec:http://bsonspec.org/

Tuesday, February 12, 13

Page 10: Node-IL Meetup 12/2

It’s A Document Oriented Data Store

Tuesday, February 12, 13

Page 11: Node-IL Meetup 12/2

It don’t do joins

Tuesday, February 12, 13

Page 12: Node-IL Meetup 12/2

It don’t do transactions

Tuesday, February 12, 13

Page 13: Node-IL Meetup 12/2

Keeping It Simple

Document Oriented

No Transactions

No Joins

Tuesday, February 12, 13

Page 14: Node-IL Meetup 12/2

What Can Mongo Do For You

Create and store objects

Arrange them in collections

Retrieve them later

Tuesday, February 12, 13

Page 15: Node-IL Meetup 12/2

Q & A

Tuesday, February 12, 13

Page 16: Node-IL Meetup 12/2

CRUD OperationsCreate, Read, Update and Destroy Data

Tuesday, February 12, 13

Page 17: Node-IL Meetup 12/2

Mongo CRUD

Create is called insert

Read is called find

Update is called update

Destroy is called remove

Tuesday, February 12, 13

Page 18: Node-IL Meetup 12/2

Mongo CRUD

db.highscore.insert ({"name":"Tom", "score":94});

db.highscore.find ({"name" : "Tom" })

db.highscore.update ({"name" : "Tom"}, {"$inc" : { "score" : 1 } });

db.highscore.remove ({"name" : "Tom"});

Tuesday, February 12, 13

Page 19: Node-IL Meetup 12/2

MongooseMongoDB + Node.JS = Awesome

Tuesday, February 12, 13

Page 20: Node-IL Meetup 12/2

What’s That

An Object Relational Mapper for Node.JS

Handles gory details so you don’t have to

Fat Models

Tuesday, February 12, 13

Page 21: Node-IL Meetup 12/2

Agenda

Hello Mongoose

Schema and Data Types

Custom Validators

Querying Data

Mongoose Plugins

Tuesday, February 12, 13

Page 22: Node-IL Meetup 12/2

Online Resources

http://mongoosejs.com/

https://github.com/LearnBoost/mongoose

irc: #mongoosejs on freenode

Tuesday, February 12, 13

Page 23: Node-IL Meetup 12/2

Hello Mongoose

var mongoose = require('mongoose');mongoose.connect('localhost', 'test');

var schema = mongoose.Schema({ name: String });var Cat = mongoose.model('Cat', schema);

var kitty = new Cat({ name: 'Zildjian' });kitty.save(function (err) { if (err) // ... console.log('meow');});

Tuesday, February 12, 13

Page 24: Node-IL Meetup 12/2

Mongoose Objects

Schema

Model Model

Schema

Model

Tuesday, February 12, 13

Page 25: Node-IL Meetup 12/2

Mongoose Objects

{ name: String}

Cat

kitty

var schema = mongoose.Schema( { name: String });

var Cat = mongoose.model( 'Cat', schema);

var kitty = new Cat( { name: 'Zildjian' });

Tuesday, February 12, 13

Page 26: Node-IL Meetup 12/2

Demo

Express + Node.JS + Mongoose

Contact List App

Tuesday, February 12, 13

Page 27: Node-IL Meetup 12/2

Schema Definitions

A schema takes a description object which specifies its keys and their types

Types are mostly normal JS

new Schema({ title: String, body: String, date: Date, hidden: Boolean, meta: { votes: Number, favs: Number }});

Tuesday, February 12, 13

Page 28: Node-IL Meetup 12/2

Schema Types

String

Number

Date

Buffer

Boolean

Mixed

ObjectId

Array

Tuesday, February 12, 13

Page 29: Node-IL Meetup 12/2

Nested Objects

Creating nested objects is easy

Just assign an object as the value

var PersonSchema = new Schema({  name: {    first: String,    last: String  }});

Tuesday, February 12, 13

Page 30: Node-IL Meetup 12/2

Array Fields

Array fields are easy

Just write the type as a single array element

var PersonSchema = new Schema({  name: {    first: String,    last: String  },  hobbies: [String]});

Tuesday, February 12, 13

Page 31: Node-IL Meetup 12/2

Schema Use Case

Let’s start writing a photo taking app

Each photo is saved in the DB as a Data URL

Along with the photo we’ll save the username

var PhotoSchema = new Schema({  username: String,  photo: String,  uploaded_at: Date}); var Photo = mongoose.model( 'Photo', PhotoSchema);

Tuesday, February 12, 13

Page 32: Node-IL Meetup 12/2

Creating New Objects

Create a new object by instantiating the model

Pass the values to the ctor

var mypic = new Photo({  username: 'ynon',  photo: 'data:image/gif;base64,R0lGODlhCwAOAMQfAP////7+',  uploaded_at: new Date()});

Tuesday, February 12, 13

Page 33: Node-IL Meetup 12/2

Creating New Objects

After the object is ready, simply save it mypic.save();

Tuesday, February 12, 13

Page 34: Node-IL Meetup 12/2

What Schema Can Do For You

Add validations on the fields

Stock validators: required, min, max

Can also create custom validators

Validation happens on save

var PhotoSchema = new Schema({  username: { type: String, required: true },  photo: { type: String, required: true },

  uploaded_at: Date});

Tuesday, February 12, 13

Page 35: Node-IL Meetup 12/2

What Schema Can Do For You

Provide default values for fields

Can use a function as default for delayed evaluation

var PhotoSchema = new Schema({  username: { type: String, required: true },  photo: { type: String, required: true },  uploaded_at: { type: Date, default: Date.now }});

Tuesday, February 12, 13

Page 36: Node-IL Meetup 12/2

Custom Validators

It’s possible to use your own validation code

var toySchema = new Schema({  color: String,  name: String}); toySchema.path('color').validate(function(value) {  return ( this.color.length % 3 === 0 );}); 

Tuesday, February 12, 13

Page 37: Node-IL Meetup 12/2

Schemas: Fat Models

Tuesday, February 12, 13

Page 38: Node-IL Meetup 12/2

What Schema Can Do For You

Add methods to your documents

var EvilZombieSchema = new Schema({  name: String,  brainz: { type: Number, default: 0 }}); EvilZombieSchema.methods.eat_brain = function() {  this.brainz += 1;}; 

Tuesday, February 12, 13

Page 39: Node-IL Meetup 12/2

Schema Create Indices

A schema can have some fields marked as “index”. The collection will be indexed by them automatically

var PhotoSchema = new Schema({  username: { type: String, required: true, index: true },  photo: { type: String, required: true },  uploaded_at: { type: Date, default: Date.now }});

Tuesday, February 12, 13

Page 40: Node-IL Meetup 12/2

Schemas Create Accessors

A virtual field is not saved in the DB, but calculated from existing fields. “full-name” is an example.

personSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last;});

personSchema.virtual('name.full').set(function (name) { var split = name.split(' '); this.name.first = split[0]; this.name.last = split[1];});

Tuesday, February 12, 13

Page 41: Node-IL Meetup 12/2

Q & A

Tuesday, February 12, 13

Page 42: Node-IL Meetup 12/2

Querying Data

Use Model#find / Model#findOne to query data

// executes immediately, passing results to callbackMyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) { // do something with data // or handle err});

Tuesday, February 12, 13

Page 43: Node-IL Meetup 12/2

Querying Data

You can also chain queries by not passing a callback

Pass the callback at the end using exec

var p = Photo.find({username: 'ynon'}).  skip(10).  limit(5).  exec(function(err, docs) {  console.dir( docs );});

Tuesday, February 12, 13

Page 44: Node-IL Meetup 12/2

Other Query Methods

find( cond, [fields], [options], [cb] )

findOne ( cond, [fields], [options], [cb] )

findById ( id, [fields], [options], [cb] )

findOneAndUpdate( cond, [update], [options], [cb] )

findOneAndRemove( cond, [options], [cb] )

Tuesday, February 12, 13

Page 45: Node-IL Meetup 12/2

Counting Matches

Use count to discover how many matching documents are in the DB

Adventure.count({ type: 'jungle' }, function (err, count) { if (err) .. console.log('there are %d jungle adventures', count);});

Tuesday, February 12, 13

Page 46: Node-IL Meetup 12/2

Mongoose Plugins

A plugin connects to the Schema and extends it in a way

Tuesday, February 12, 13

Page 47: Node-IL Meetup 12/2

Mongoose Plugins

A mongoose plugin is a simple function which takes schema and options

Demo: lastModifiedPluginhttps://gist.github.com/4657579

Tuesday, February 12, 13

Page 48: Node-IL Meetup 12/2

Mongoose Plugins

find or create plugin:

https://github.com/drudge/mongoose-findorcreate

Tuesday, February 12, 13

Page 49: Node-IL Meetup 12/2

Mongoose Plugins

Hashed password field plugin:https://gist.github.com/4658951

Tuesday, February 12, 13

Page 50: Node-IL Meetup 12/2

Mongoose Plugins

Mongoose troops is a collection of useful mongoose plugins:https://github.com/tblobaum/mongoose-troop

Tuesday, February 12, 13

Page 51: Node-IL Meetup 12/2

Thanks For Listening

Ynon Perek

Slides at:ynonperek.com

Talk to me at: [email protected]

Tuesday, February 12, 13