0
Getting Started With                           MongoDB and                           Mongoose                           { ...
Whoami                     Ynon Perek                     http://ynonperek.com                     ynon@ynonperek.comTuesd...
Agenda                                Mongo Is Awesome                                CRUD Operations                     ...
COUC H DB             CASSANDRA                   Part of the NoSQL Family                                                ...
But Most Popular Of AllTuesday, February 12, 13
Mongo Is Awesome                  Data Store for                  JSON ObjectsTuesday, February 12, 13
Mongo Is Awesome                  Data Store for                  JSON Objects          {               “Name” : “Rose Tyl...
JSON Objects                     A JSON Object is a                     collection of key/                     value pairs...
Mongo saves the data                     in a binary format                     called BSON                     Spec:     ...
It’s A Document Oriented Data                 StoreTuesday, February 12, 13
It don’t do joinsTuesday, February 12, 13
It don’t do transactionsTuesday, February 12, 13
Keeping It Simple                     Document Oriented                     No Transactions                     No JoinsTu...
What Can Mongo Do For You                     Create and store objects                     Arrange them in collections    ...
Q&ATuesday, February 12, 13
CRUD Operations                           Create, Read, Update and Destroy DataTuesday, February 12, 13
Mongo CRUD                     Create   is called insert                     Read     is called find                     U...
Mongo CRUD                     db.highscore.insert ({"name":"Tom", "score":94});                     db.highscore.find   (...
Mongoose                           MongoDB + Node.JS = AwesomeTuesday, February 12, 13
What’s That                     An Object Relational Mapper for Node.JS                     Handles gory details so you do...
Agenda                     Hello Mongoose                     Schema and Data Types                     Custom Validators ...
Online Resources                     http://mongoosejs.com/                     https://github.com/LearnBoost/mongoose    ...
Hello Mongoose             var mongoose = require(mongoose);             mongoose.connect(localhost, test);             va...
Mongoose Objects                              Schema            Schema                      Model            Model   Model...
Mongoose Objects            var schema = mongoose.Schema(                          { name: String });                     ...
Demo                     Express + Node.JS +                     Mongoose                     Contact List AppTuesday, Feb...
Schema Definitions                                                new Schema({                                            ...
Schema Types                     String                     Number                     Date                     Buffer    ...
Nested Objects                                                var PersonSchema = new Schema({                     Creating...
Array Fields                                                var PersonSchema = new Schema({                     Array fiel...
Schema Use Case                     Let’s start writing a                     photo taking app        var PhotoSchema = ne...
Creating New Objects                     Create a new object    var mypic = new Photo({                     by instantiati...
Creating New Objects                     After the object is                     ready, simply save it                    ...
What Schema Can Do For You                     Add validations on   var PhotoSchema = new Schema({                     the...
What Schema Can Do For You                     Provide default     var PhotoSchema = new Schema({                     valu...
Custom Validators                     It’s possible to use your own validation code             var toySchema = new Schema...
Schemas: Fat ModelsTuesday, February 12, 13
What Schema Can Do For You                     Add methods to your documents             var EvilZombieSchema = new Schema...
Schema Create Indices                     A schema can have some fields marked as “index”. The                     collect...
Schemas Create Accessors                     A virtual field is not saved in the DB, but calculated from                  ...
Q&ATuesday, February 12, 13
Querying Data                     Use Model#find / Model#findOne to query data          // executes immediately, passing r...
Querying Data                     You can also chain queries by not passing a callback                     Pass the callba...
Other Query Methods                     find( cond, [fields], [options], [cb] )                     findOne ( cond, [field...
Counting Matches                     Use count to discover how many matching documents                     are in the DB  ...
Mongoose Plugins                     A plugin connects to                     the Schema and                     extends i...
Mongoose Plugins                     A mongoose plugin is a simple function which takes                     schema and opt...
Mongoose Plugins                     find or create plugin:                     https://github.com/drudge/mongoose-findorc...
Mongoose Plugins                     Hashed password field plugin:                     https://gist.github.com/4658951Tues...
Mongoose Plugins                     Mongoose troops is a collection of useful mongoose                     plugins:      ...
Thanks For Listening                     Ynon Perek                     Slides at:                     ynonperek.com      ...
Upcoming SlideShare
Loading in...5
×

Node-IL Meetup 12/2

744

Published on

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
744
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
8
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Node-IL Meetup 12/2"

  1. 1. Getting Started With MongoDB and Mongoose { author: “Ynon Perek” }Tuesday, February 12, 13
  2. 2. Whoami Ynon Perek http://ynonperek.com ynon@ynonperek.comTuesday, February 12, 13
  3. 3. Agenda Mongo Is Awesome CRUD Operations Mongoose Coding TimeTuesday, February 12, 13
  4. 4. COUC H DB CASSANDRA Part of the NoSQL Family SIMPLEDB REDIS FLOCKD BTuesday, February 12, 13
  5. 5. But Most Popular Of AllTuesday, February 12, 13
  6. 6. Mongo Is Awesome Data Store for JSON ObjectsTuesday, February 12, 13
  7. 7. Mongo Is Awesome Data Store for JSON Objects { “Name” : “Rose Tyler” }Tuesday, February 12, 13
  8. 8. JSON Objects A JSON Object is a collection of key/ value pairs {   "name" : "Rose Tyler", Keys are simple   "race" : "Human", strings   "body parts" : [ "head", "legs"] } Values can be: Numbers, Strings, Arrays, Other Objects, and moreTuesday, February 12, 13
  9. 9. Mongo saves the data in a binary format called BSON Spec: http://bsonspec.org/Tuesday, February 12, 13
  10. 10. It’s A Document Oriented Data StoreTuesday, February 12, 13
  11. 11. It don’t do joinsTuesday, February 12, 13
  12. 12. It don’t do transactionsTuesday, February 12, 13
  13. 13. Keeping It Simple Document Oriented No Transactions No JoinsTuesday, February 12, 13
  14. 14. What Can Mongo Do For You Create and store objects Arrange them in collections Retrieve them laterTuesday, February 12, 13
  15. 15. Q&ATuesday, February 12, 13
  16. 16. CRUD Operations Create, Read, Update and Destroy DataTuesday, February 12, 13
  17. 17. Mongo CRUD Create is called insert Read is called find Update is called update Destroy is called removeTuesday, February 12, 13
  18. 18. 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
  19. 19. Mongoose MongoDB + Node.JS = AwesomeTuesday, February 12, 13
  20. 20. What’s That An Object Relational Mapper for Node.JS Handles gory details so you don’t have to Fat ModelsTuesday, February 12, 13
  21. 21. Agenda Hello Mongoose Schema and Data Types Custom Validators Querying Data Mongoose PluginsTuesday, February 12, 13
  22. 22. Online Resources http://mongoosejs.com/ https://github.com/LearnBoost/mongoose irc: #mongoosejs on freenodeTuesday, February 12, 13
  23. 23. 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
  24. 24. Mongoose Objects Schema Schema Model Model ModelTuesday, February 12, 13
  25. 25. Mongoose Objects var schema = mongoose.Schema( { name: String }); { name: String} var Cat = mongoose.model( Cat, schema); Cat var kitty = new Cat( { name: Zildjian }); kittyTuesday, February 12, 13
  26. 26. Demo Express + Node.JS + Mongoose Contact List AppTuesday, February 12, 13
  27. 27. Schema Definitions new Schema({ title: String, A schema takes a body: String, description object date: Date, which specifies its keys hidden: Boolean, and their types meta: { votes: Number, Types are mostly favs: Number normal JS } });Tuesday, February 12, 13
  28. 28. Schema Types String Number Date Buffer Boolean Mixed ObjectId ArrayTuesday, February 12, 13
  29. 29. Nested Objects var PersonSchema = new Schema({ Creating nested objects   name: {     first: String, is easy     last: String   } Just assign an object as }); the valueTuesday, February 12, 13
  30. 30. Array Fields var PersonSchema = new Schema({ Array fields are easy   name: {     first: String,     last: String Just write the type as a   }, single array element   hobbies: [String] });Tuesday, February 12, 13
  31. 31. Schema Use Case Let’s start writing a photo taking app var PhotoSchema = new Schema({   username: String, Each photo is saved   photo: String, in the DB as a Data   uploaded_at: Date URL });   var Photo = mongoose.model( Along with the Photo, PhotoSchema); photo we’ll save the usernameTuesday, February 12, 13
  32. 32. Creating New Objects Create a new object var mypic = new Photo({ by instantiating the   username: ynon,   photo: data:image/ model gif;base64,R0lGOD lhCwAOAMQfAP////7+, Pass the values to   uploaded_at: new Date() the ctor });Tuesday, February 12, 13
  33. 33. Creating New Objects After the object is ready, simply save it mypic.save();Tuesday, February 12, 13
  34. 34. What Schema Can Do For You Add validations on var PhotoSchema = new Schema({ the fields   username: { type: String, required: true }, Stock validators:   photo: { type: String, required: true }, required, min, max   uploaded_at: Date Can also create }); custom validators Validation happens on saveTuesday, February 12, 13
  35. 35. What Schema Can Do For You Provide default var PhotoSchema = new Schema({ values for fields   username: { type: String, required: true }, Can use a   photo: function as { type: String, required: true }, default for   uploaded_at: { type: Date, default: Date.now } delayed }); evaluationTuesday, February 12, 13
  36. 36. 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
  37. 37. Schemas: Fat ModelsTuesday, February 12, 13
  38. 38. 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
  39. 39. 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
  40. 40. 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
  41. 41. Q&ATuesday, February 12, 13
  42. 42. Querying Data Use Model#find / Model#findOne to query data // executes immediately, passing results to callback MyModel.find({ name: john, age: { $gte: 18 }}, function (err, docs) { // do something with data // or handle err });Tuesday, February 12, 13
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. Mongoose Plugins A plugin connects to the Schema and extends it in a wayTuesday, February 12, 13
  47. 47. Mongoose Plugins A mongoose plugin is a simple function which takes schema and options Demo: lastModifiedPlugin https://gist.github.com/4657579Tuesday, February 12, 13
  48. 48. Mongoose Plugins find or create plugin: https://github.com/drudge/mongoose-findorcreateTuesday, February 12, 13
  49. 49. Mongoose Plugins Hashed password field plugin: https://gist.github.com/4658951Tuesday, February 12, 13
  50. 50. Mongoose Plugins Mongoose troops is a collection of useful mongoose plugins: https://github.com/tblobaum/mongoose-troopTuesday, February 12, 13
  51. 51. Thanks For Listening Ynon Perek Slides at: ynonperek.com Talk to me at: ynon@ynonperek.comTuesday, February 12, 13
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×