SlideShare a Scribd company logo
1 of 51
Download to read offline
Getting Started With
                           MongoDB and
                           Mongoose
                           { author: “Ynon Perek” }




Tuesday, February 12, 13
Whoami




                     Ynon Perek

                     http://ynonperek.com

                     ynon@ynonperek.com




Tuesday, February 12, 13
Agenda



                                Mongo Is Awesome

                                CRUD Operations

                                Mongoose

                                Coding Time




Tuesday, February 12, 13
COUC H DB             CASSANDRA



                   Part of the NoSQL Family

                                                      SIMPLEDB
                           REDIS

                                         FLOCKD
                                               B


Tuesday, February 12, 13
But Most Popular Of All




Tuesday, February 12, 13
Mongo Is Awesome



                  Data Store for
                  JSON Objects




Tuesday, February 12, 13
Mongo Is Awesome



                  Data Store for
                  JSON Objects


          {
               “Name” : “Rose Tyler”
          }




Tuesday, February 12, 13
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 more




Tuesday, February 12, 13
Mongo saves the data
                     in a binary format
                     called BSON

                     Spec:
                     http://bsonspec.org/




Tuesday, February 12, 13
It’s A Document Oriented Data
                 Store




Tuesday, February 12, 13
It don’t do joins




Tuesday, February 12, 13
It don’t do transactions




Tuesday, February 12, 13
Keeping It Simple




                     Document Oriented

                     No Transactions

                     No Joins




Tuesday, February 12, 13
What Can Mongo Do For You




                     Create and store objects

                     Arrange them in collections

                     Retrieve them later




Tuesday, February 12, 13
Q&A




Tuesday, February 12, 13
CRUD Operations
                           Create, Read, Update and Destroy Data


Tuesday, February 12, 13
Mongo CRUD



                     Create   is called insert

                     Read     is called find

                     Update is called update

                     Destroy is called remove




Tuesday, February 12, 13
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
Mongoose
                           MongoDB + Node.JS = Awesome


Tuesday, February 12, 13
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
Agenda


                     Hello Mongoose

                     Schema and Data Types

                     Custom Validators

                     Querying Data

                     Mongoose Plugins




Tuesday, February 12, 13
Online Resources




                     http://mongoosejs.com/

                     https://github.com/LearnBoost/mongoose

                     irc: #mongoosejs on freenode




Tuesday, February 12, 13
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
Mongoose Objects


                              Schema            Schema




                      Model            Model   Model




Tuesday, February 12, 13
Mongoose Objects

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


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


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




Tuesday, February 12, 13
Demo




                     Express + Node.JS +
                     Mongoose

                     Contact List App




Tuesday, February 12, 13
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
Schema Types

                     String

                     Number

                     Date

                     Buffer

                     Boolean

                     Mixed

                     ObjectId

                     Array



Tuesday, February 12, 13
Nested Objects



                                                var PersonSchema = new Schema({
                     Creating nested objects      name: {
                                                    first: String,
                     is easy
                                                    last: String
                                                  }
                     Just assign an object as   });
                     the value




Tuesday, February 12, 13
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
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
                     username




Tuesday, February 12, 13
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
Creating New Objects




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




Tuesday, February 12, 13
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 save




Tuesday, February 12, 13
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
                                         });
                     evaluation




Tuesday, February 12, 13
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
Schemas: Fat Models


Tuesday, February 12, 13
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
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
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
Q&A




Tuesday, February 12, 13
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
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
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
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
Mongoose Plugins




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




Tuesday, February 12, 13
Mongoose Plugins




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

                     Demo: lastModifiedPlugin
                     https://gist.github.com/4657579




Tuesday, February 12, 13
Mongoose Plugins




                     find or create plugin:

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




Tuesday, February 12, 13
Mongoose Plugins




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




Tuesday, February 12, 13
Mongoose Plugins




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




Tuesday, February 12, 13
Thanks For Listening



                     Ynon Perek

                     Slides at:
                     ynonperek.com

                     Talk to me at:
                     ynon@ynonperek.com




Tuesday, February 12, 13

More Related Content

What's hot

Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseYnon Perek
 
Solr, Lucene and Hadoop @ Etsy
Solr, Lucene and Hadoop @ EtsySolr, Lucene and Hadoop @ Etsy
Solr, Lucene and Hadoop @ Etsylucenerevolution
 
MongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseMongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseRuben Inoto Soto
 
Bookmarklet型(云端)应用的前端架构
Bookmarklet型(云端)应用的前端架构Bookmarklet型(云端)应用的前端架构
Bookmarklet型(云端)应用的前端架构Chappell.Wat
 
Data normalization & memoized denormalization
Data normalization & memoized denormalizationData normalization & memoized denormalization
Data normalization & memoized denormalizationSalsita Software
 
Webinar: MongoDB on the JVM
Webinar: MongoDB on the JVMWebinar: MongoDB on the JVM
Webinar: MongoDB on the JVMMongoDB
 
Dev Jumpstart: Schema Design Best Practices
Dev Jumpstart: Schema Design Best PracticesDev Jumpstart: Schema Design Best Practices
Dev Jumpstart: Schema Design Best PracticesMongoDB
 

What's hot (8)

Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and Mongoose
 
Json tutorial
Json tutorialJson tutorial
Json tutorial
 
Solr, Lucene and Hadoop @ Etsy
Solr, Lucene and Hadoop @ EtsySolr, Lucene and Hadoop @ Etsy
Solr, Lucene and Hadoop @ Etsy
 
MongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseMongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL Database
 
Bookmarklet型(云端)应用的前端架构
Bookmarklet型(云端)应用的前端架构Bookmarklet型(云端)应用的前端架构
Bookmarklet型(云端)应用的前端架构
 
Data normalization & memoized denormalization
Data normalization & memoized denormalizationData normalization & memoized denormalization
Data normalization & memoized denormalization
 
Webinar: MongoDB on the JVM
Webinar: MongoDB on the JVMWebinar: MongoDB on the JVM
Webinar: MongoDB on the JVM
 
Dev Jumpstart: Schema Design Best Practices
Dev Jumpstart: Schema Design Best PracticesDev Jumpstart: Schema Design Best Practices
Dev Jumpstart: Schema Design Best Practices
 

Viewers also liked

Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongooseFin Chen
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichAWS Germany
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Brightaaronheckmann
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in InsuranceCognizant
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM CapabilitiesArlene DeMita
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer ExperienceCognizant
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structureSOuvagya Kumar Jena
 

Viewers also liked (12)

Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongoose
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Express JS
Express JSExpress JS
Express JS
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science Bereich
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Bright
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM Capabilities
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structure
 
Express js
Express jsExpress js
Express js
 

Similar to Getting Started With MongoDB and Mongoose

Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDBYnon Perek
 
MongoDB For C++ Developers
MongoDB For C++ DevelopersMongoDB For C++ Developers
MongoDB For C++ DevelopersYnon Perek
 
Municipal Government Meets NoSQL
Municipal Government Meets NoSQLMunicipal Government Meets NoSQL
Municipal Government Meets NoSQLMongoDB
 
Simonvc basho-nosql-in-a-continuous-delivery-world
Simonvc basho-nosql-in-a-continuous-delivery-worldSimonvc basho-nosql-in-a-continuous-delivery-world
Simonvc basho-nosql-in-a-continuous-delivery-worldSimon Vans-Colina
 
Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013   Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013 Pablo Godel
 
Big data + mobile + social
Big data + mobile + socialBig data + mobile + social
Big data + mobile + social[x]cube LABS
 
Augmented Reality with JavaScript and Appcelerator Titanium
Augmented Reality with JavaScript and Appcelerator TitaniumAugmented Reality with JavaScript and Appcelerator Titanium
Augmented Reality with JavaScript and Appcelerator TitaniumJeff Bonnes
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeSpyros Passas
 

Similar to Getting Started With MongoDB and Mongoose (9)

Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
 
MongoDB For C++ Developers
MongoDB For C++ DevelopersMongoDB For C++ Developers
MongoDB For C++ Developers
 
Municipal Government Meets NoSQL
Municipal Government Meets NoSQLMunicipal Government Meets NoSQL
Municipal Government Meets NoSQL
 
Simonvc basho-nosql-in-a-continuous-delivery-world
Simonvc basho-nosql-in-a-continuous-delivery-worldSimonvc basho-nosql-in-a-continuous-delivery-world
Simonvc basho-nosql-in-a-continuous-delivery-world
 
Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013   Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013
 
Big data + mobile + social
Big data + mobile + socialBig data + mobile + social
Big data + mobile + social
 
Augmented Reality with JavaScript and Appcelerator Titanium
Augmented Reality with JavaScript and Appcelerator TitaniumAugmented Reality with JavaScript and Appcelerator Titanium
Augmented Reality with JavaScript and Appcelerator Titanium
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappe
 
Curious case of Dust
Curious case of DustCurious case of Dust
Curious case of Dust
 

More from Ynon Perek

09 performance
09 performance09 performance
09 performanceYnon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web IntroYnon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile DevicesYnon Perek
 
Architecture app
Architecture appArchitecture app
Architecture appYnon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and RubyYnon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application TestingYnon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application SecurityYnon Perek
 

More from Ynon Perek (20)

Regexp
RegexpRegexp
Regexp
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 
09 performance
09 performance09 performance
09 performance
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Vimperl
VimperlVimperl
Vimperl
 
Syllabus
SyllabusSyllabus
Syllabus
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
 
Network
NetworkNetwork
Network
 
Architecture app
Architecture appArchitecture app
Architecture app
 
Cryptography
CryptographyCryptography
Cryptography
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
 
Accessibility
AccessibilityAccessibility
Accessibility
 
Angularjs
AngularjsAngularjs
Angularjs
 
Js memory
Js memoryJs memory
Js memory
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
[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.pdfhans926745
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
[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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Getting Started With MongoDB and Mongoose

  • 1. Getting Started With MongoDB and Mongoose { author: “Ynon Perek” } Tuesday, February 12, 13
  • 2. Whoami Ynon Perek http://ynonperek.com ynon@ynonperek.com Tuesday, February 12, 13
  • 3. Agenda Mongo Is Awesome CRUD Operations Mongoose Coding Time Tuesday, February 12, 13
  • 4. COUC H DB CASSANDRA Part of the NoSQL Family SIMPLEDB REDIS FLOCKD B Tuesday, February 12, 13
  • 5. But Most Popular Of All Tuesday, February 12, 13
  • 6. Mongo Is Awesome Data Store for JSON Objects Tuesday, February 12, 13
  • 7. Mongo Is Awesome Data Store for JSON Objects { “Name” : “Rose Tyler” } Tuesday, February 12, 13
  • 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 more Tuesday, February 12, 13
  • 9. Mongo saves the data in a binary format called BSON Spec: http://bsonspec.org/ Tuesday, February 12, 13
  • 10. It’s A Document Oriented Data Store Tuesday, February 12, 13
  • 11. It don’t do joins Tuesday, February 12, 13
  • 12. It don’t do transactions Tuesday, February 12, 13
  • 13. Keeping It Simple Document Oriented No Transactions No Joins Tuesday, February 12, 13
  • 14. What Can Mongo Do For You Create and store objects Arrange them in collections Retrieve them later Tuesday, February 12, 13
  • 16. CRUD Operations Create, Read, Update and Destroy Data Tuesday, February 12, 13
  • 17. Mongo CRUD Create is called insert Read is called find Update is called update Destroy is called remove Tuesday, February 12, 13
  • 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. Mongoose MongoDB + Node.JS = Awesome Tuesday, February 12, 13
  • 20. 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
  • 21. Agenda Hello Mongoose Schema and Data Types Custom Validators Querying Data Mongoose Plugins Tuesday, February 12, 13
  • 22. Online Resources http://mongoosejs.com/ https://github.com/LearnBoost/mongoose irc: #mongoosejs on freenode Tuesday, February 12, 13
  • 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. Mongoose Objects Schema Schema Model Model Model Tuesday, February 12, 13
  • 25. Mongoose Objects var schema = mongoose.Schema( { name: String }); { name: String} var Cat = mongoose.model( 'Cat', schema); Cat var kitty = new Cat( { name: 'Zildjian' }); kitty Tuesday, February 12, 13
  • 26. Demo Express + Node.JS + Mongoose Contact List App Tuesday, February 12, 13
  • 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. Schema Types String Number Date Buffer Boolean Mixed ObjectId Array Tuesday, February 12, 13
  • 29. Nested Objects var PersonSchema = new Schema({ Creating nested objects   name: {     first: String, is easy     last: String   } Just assign an object as }); the value Tuesday, February 12, 13
  • 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. 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 username Tuesday, February 12, 13
  • 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. Creating New Objects After the object is ready, simply save it mypic.save(); Tuesday, February 12, 13
  • 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 save Tuesday, February 12, 13
  • 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 }); evaluation Tuesday, February 12, 13
  • 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. Schemas: Fat Models Tuesday, February 12, 13
  • 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. 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. 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
  • 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. 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. 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. 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. Mongoose Plugins A plugin connects to the Schema and extends it in a way Tuesday, February 12, 13
  • 47. Mongoose Plugins A mongoose plugin is a simple function which takes schema and options Demo: lastModifiedPlugin https://gist.github.com/4657579 Tuesday, February 12, 13
  • 48. Mongoose Plugins find or create plugin: https://github.com/drudge/mongoose-findorcreate Tuesday, February 12, 13
  • 49. Mongoose Plugins Hashed password field plugin: https://gist.github.com/4658951 Tuesday, February 12, 13
  • 50. Mongoose Plugins Mongoose troops is a collection of useful mongoose plugins: https://github.com/tblobaum/mongoose-troop Tuesday, February 12, 13
  • 51. Thanks For Listening Ynon Perek Slides at: ynonperek.com Talk to me at: ynon@ynonperek.com Tuesday, February 12, 13