SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Mongoose: MongoDB object
modelling for Node.js

Speaker: Yuriy Bogomolov
Solution Engineer at Sitecore Ukraine
@YuriyBogomolov | fb.me/yuriy.bogomolov
Agenda
1. Short intro: what is Node.js.
2. Main inconveniences of using the native MongoDB driver for Node.js.
3. Mongoose: what is it and what are its killer features:
•
•
•
•
•
•

Validation
Casting
Encapsulation
Middlewares (lifecycle management)
Population
Query building

4. Schema-Driven Design for your applications.
5. Useful links and Q&A
03.03.2014

MongoDB Meetup Dnipropetrovsk

2 /16
1. Intro to Node.js
• Node.js is a server-side JavaScript execution
environment.
• Uses asynchronous event-driven model.
• Major accent on non-blocking operations for
I/O and DB access.
• Based on Google’s V8 Engine.
• Open-source
• Has own package management system — NPM.
• Fast, highly scalable, robust environment.
03.03.2014

MongoDB Meetup Dnipropetrovsk

3 /16
2. Main inconveniences of native MongoDB driver
• No data validation
• No casting during inserts
• No encapsulation
• No references (joins)

03.03.2014

MongoDB Meetup Dnipropetrovsk

4 /16
3. What is Mongoose
• Object Data Modelling (ODM) for Node.js
• Officially supported by 10gen, Inc.
• Features:
•
•
•
•
•

Async and sync validation of models
Model casting
Object lifecycle management (middlewares)
Pseudo-joins!
Query builder

npm install mongoose

03.03.2014

MongoDB Meetup Dnipropetrovsk

5 /16
3. Mongoose setup
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mycollection');
var Schema = mongoose.Schema;
var PostSchema = new Schema({
title: { type: String, required: true },
body: { type: String, required: true },
author: { type: ObjectId, required: true, ref: 'User' },
tags: [String],
date: { type: Date, default: Date.now }
});

Reference
Simplified declaration
Default value

mongoose.model('Post', PostSchema);

03.03.2014

Validation of presence

MongoDB Meetup Dnipropetrovsk

6 /16
3. Mongoose features: validation
Simplest validation example: presence
var UserSchema = new Schema({ name: { type: String, required: true } });
var UserSchema = new Schema({ name: { type: String, required: 'Oh snap! Name is required.' } });

Passing validation function:
var UserSchema = new Schema({ name: { type: String, validator: validate } });
var validate = function (value) { /*...*/ }; // synchronous validator
var validateAsync = function (value, respond) { respond(false); }; // async validator

Via .path() API call:
UserSchema.path('email').validate(function (email, respond) {
var User = mongoose.model('User');
User.find({ email: email }).exec(function (err, users) {
return respond(!err && users.length === 0);
});
}, 'Such email is already registered');
03.03.2014

MongoDB Meetup Dnipropetrovsk

7 /16
3. Mongoose features: casting
• Each property is cast to its
mapped SchemaType in the
document, obtained by the query.
• Valid SchemaTypes are:
•
•
•
•
•
•
•
•

String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array

03.03.2014

var PostSchema = new Schema({
_id: ObjectId, // implicitly exists
title: { type: String, required: true },
body: { type: String, required: true },
author: { type: ObjectId, required: true, ref: 'User' },
tags: [String],
date: { type: Date, default: Date.now },
is_featured: { type: Boolean, default: false }
});

MongoDB Meetup Dnipropetrovsk

8 /16
3. Mongoose features: encapsulation
Models can have static methods and instance methods:
PostSchema.statics = {
dropAllPosts: function (areYouSure) {
// drop the posts!
}
};

03.03.2014

PostSchema.methods = {
addComment: function (user, comment,
callback) {
// add comment here
},
removeComment: function (user,
comment, callback) {
// remove comment here
}
};

MongoDB Meetup Dnipropetrovsk

9 /16
3. Mongoose features: lifecycle management
Models have .pre() and .post() middlewares, which can hook custom
functions to init, save, validate and remove model methods:
schema.pre('save', true, function (next, done) {
// calling next kicks off the next middleware in parallel
next();
doAsync(done);
});

schema.post('save', function (doc) {
console.log('%s has been saved', doc._id);
});

03.03.2014

MongoDB Meetup Dnipropetrovsk

10 /16
3. Mongoose features: population
Population is the process of automatically replacing the specified paths
in the document with document(s) from other collection(s):
PostSchema.statics = {
load: function (permalink, callback) {
this.findOne({ permalink: permalink })
.populate('author', 'username avatar_url')
.populate('comments', 'author body date')
.exec(callback);
}
};

03.03.2014

MongoDB Meetup Dnipropetrovsk

11 /16
3. Mongoose features: query building
Different methods could be stacked one upon the other, but the query
itself will be generated and executed only after .exec():
var options = {
perPage: 10,
page: 1
};
this.find(criteria)
.populate('author', 'username')
.sort({'date_published': -1})
.limit(options.perPage)
.skip(options.perPage * options.page)
.exec(callback);

03.03.2014

MongoDB Meetup Dnipropetrovsk

12 /16
4. Schema-Driven Design for your applications
• Schemas should match data-access patterns of your
application.
• You should pre-join data where it’s possible (and use Mongoose’s
.populate() wisely!).
• You have no constraints and transactions — keep that in mind.
• Using Mongoose for designing your application’s Schemas is similar to
OOP design of your code.

03.03.2014

MongoDB Meetup Dnipropetrovsk

13 /16
Useful links
• Node.js GitHub repo: https://github.com/joyent/node
• Mongoose GitHub repo: https://github.com/learnboost/mongoose
• Mongoose API docs and tutorials: http://mongoosejs.com/
• MongoDB native Node.js driver docs:
http://mongodb.github.io/node-mongodb-native/

03.03.2014

MongoDB Meetup Dnipropetrovsk

14 /16
Any questions?

03.03.2014

MongoDB Meetup Dnipropetrovsk

15 /16
MongoDB Meetup Dnipropetrovsk

Weitere ähnliche Inhalte

Was ist angesagt?

MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
Spring Security
Spring SecuritySpring Security
Spring SecurityBoy Tech
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Svetlin Nakov
 
Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Kyoung Up Jung
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축Youngil Cho
 
Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Jean-Baptiste Vigneron
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정Arawn Park
 
[132] rust
[132] rust[132] rust
[132] rustNAVER D2
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golangBo-Yi Wu
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...Edureka!
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architectureBishal Khanal
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 

Was ist angesagt? (20)

JSON WEB TOKEN
JSON WEB TOKENJSON WEB TOKEN
JSON WEB TOKEN
 
Express JS
Express JSExpress JS
Express JS
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
 
Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6Une introduction à Javascript et ECMAScript 6
Une introduction à Javascript et ECMAScript 6
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정
 
[132] rust
[132] rust[132] rust
[132] rust
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
MongoDB
MongoDBMongoDB
MongoDB
 

Ähnlich wie Mongoose: MongoDB object modelling for Node.js

Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
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 StackMongoDB
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergTestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergXebia Nederland BV
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
A Story about AngularJS modularization development
A Story about AngularJS modularization developmentA Story about AngularJS modularization development
A Story about AngularJS modularization developmentJohannes Weber
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)Chris Clarke
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
Building a scalable web application by combining modern front-end stuff and A...
Building a scalable web application by combining modern front-end stuff and A...Building a scalable web application by combining modern front-end stuff and A...
Building a scalable web application by combining modern front-end stuff and A...Chris Klug
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBMongoDB
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsRichard Rodger
 

Ähnlich wie Mongoose: MongoDB object modelling for Node.js (20)

Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
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
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergTestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
 
AngularJS
AngularJSAngularJS
AngularJS
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
A Story about AngularJS modularization development
A Story about AngularJS modularization developmentA Story about AngularJS modularization development
A Story about AngularJS modularization development
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Building a scalable web application by combining modern front-end stuff and A...
Building a scalable web application by combining modern front-end stuff and A...Building a scalable web application by combining modern front-end stuff and A...
Building a scalable web application by combining modern front-end stuff and A...
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDB
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 

Kürzlich hochgeladen

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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 RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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 slidevu2urc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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 Servicegiselly40
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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 Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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 Nanonetsnaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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...Igalia
 
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.pdfEnterprise Knowledge
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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...Miguel Araújo
 

Kürzlich hochgeladen (20)

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
 
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 ...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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 Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 

Mongoose: MongoDB object modelling for Node.js

  • 1. Mongoose: MongoDB object modelling for Node.js Speaker: Yuriy Bogomolov Solution Engineer at Sitecore Ukraine @YuriyBogomolov | fb.me/yuriy.bogomolov
  • 2. Agenda 1. Short intro: what is Node.js. 2. Main inconveniences of using the native MongoDB driver for Node.js. 3. Mongoose: what is it and what are its killer features: • • • • • • Validation Casting Encapsulation Middlewares (lifecycle management) Population Query building 4. Schema-Driven Design for your applications. 5. Useful links and Q&A 03.03.2014 MongoDB Meetup Dnipropetrovsk 2 /16
  • 3. 1. Intro to Node.js • Node.js is a server-side JavaScript execution environment. • Uses asynchronous event-driven model. • Major accent on non-blocking operations for I/O and DB access. • Based on Google’s V8 Engine. • Open-source • Has own package management system — NPM. • Fast, highly scalable, robust environment. 03.03.2014 MongoDB Meetup Dnipropetrovsk 3 /16
  • 4. 2. Main inconveniences of native MongoDB driver • No data validation • No casting during inserts • No encapsulation • No references (joins) 03.03.2014 MongoDB Meetup Dnipropetrovsk 4 /16
  • 5. 3. What is Mongoose • Object Data Modelling (ODM) for Node.js • Officially supported by 10gen, Inc. • Features: • • • • • Async and sync validation of models Model casting Object lifecycle management (middlewares) Pseudo-joins! Query builder npm install mongoose 03.03.2014 MongoDB Meetup Dnipropetrovsk 5 /16
  • 6. 3. Mongoose setup var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mycollection'); var Schema = mongoose.Schema; var PostSchema = new Schema({ title: { type: String, required: true }, body: { type: String, required: true }, author: { type: ObjectId, required: true, ref: 'User' }, tags: [String], date: { type: Date, default: Date.now } }); Reference Simplified declaration Default value mongoose.model('Post', PostSchema); 03.03.2014 Validation of presence MongoDB Meetup Dnipropetrovsk 6 /16
  • 7. 3. Mongoose features: validation Simplest validation example: presence var UserSchema = new Schema({ name: { type: String, required: true } }); var UserSchema = new Schema({ name: { type: String, required: 'Oh snap! Name is required.' } }); Passing validation function: var UserSchema = new Schema({ name: { type: String, validator: validate } }); var validate = function (value) { /*...*/ }; // synchronous validator var validateAsync = function (value, respond) { respond(false); }; // async validator Via .path() API call: UserSchema.path('email').validate(function (email, respond) { var User = mongoose.model('User'); User.find({ email: email }).exec(function (err, users) { return respond(!err && users.length === 0); }); }, 'Such email is already registered'); 03.03.2014 MongoDB Meetup Dnipropetrovsk 7 /16
  • 8. 3. Mongoose features: casting • Each property is cast to its mapped SchemaType in the document, obtained by the query. • Valid SchemaTypes are: • • • • • • • • String Number Date Buffer Boolean Mixed ObjectId Array 03.03.2014 var PostSchema = new Schema({ _id: ObjectId, // implicitly exists title: { type: String, required: true }, body: { type: String, required: true }, author: { type: ObjectId, required: true, ref: 'User' }, tags: [String], date: { type: Date, default: Date.now }, is_featured: { type: Boolean, default: false } }); MongoDB Meetup Dnipropetrovsk 8 /16
  • 9. 3. Mongoose features: encapsulation Models can have static methods and instance methods: PostSchema.statics = { dropAllPosts: function (areYouSure) { // drop the posts! } }; 03.03.2014 PostSchema.methods = { addComment: function (user, comment, callback) { // add comment here }, removeComment: function (user, comment, callback) { // remove comment here } }; MongoDB Meetup Dnipropetrovsk 9 /16
  • 10. 3. Mongoose features: lifecycle management Models have .pre() and .post() middlewares, which can hook custom functions to init, save, validate and remove model methods: schema.pre('save', true, function (next, done) { // calling next kicks off the next middleware in parallel next(); doAsync(done); }); schema.post('save', function (doc) { console.log('%s has been saved', doc._id); }); 03.03.2014 MongoDB Meetup Dnipropetrovsk 10 /16
  • 11. 3. Mongoose features: population Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s): PostSchema.statics = { load: function (permalink, callback) { this.findOne({ permalink: permalink }) .populate('author', 'username avatar_url') .populate('comments', 'author body date') .exec(callback); } }; 03.03.2014 MongoDB Meetup Dnipropetrovsk 11 /16
  • 12. 3. Mongoose features: query building Different methods could be stacked one upon the other, but the query itself will be generated and executed only after .exec(): var options = { perPage: 10, page: 1 }; this.find(criteria) .populate('author', 'username') .sort({'date_published': -1}) .limit(options.perPage) .skip(options.perPage * options.page) .exec(callback); 03.03.2014 MongoDB Meetup Dnipropetrovsk 12 /16
  • 13. 4. Schema-Driven Design for your applications • Schemas should match data-access patterns of your application. • You should pre-join data where it’s possible (and use Mongoose’s .populate() wisely!). • You have no constraints and transactions — keep that in mind. • Using Mongoose for designing your application’s Schemas is similar to OOP design of your code. 03.03.2014 MongoDB Meetup Dnipropetrovsk 13 /16
  • 14. Useful links • Node.js GitHub repo: https://github.com/joyent/node • Mongoose GitHub repo: https://github.com/learnboost/mongoose • Mongoose API docs and tutorials: http://mongoosejs.com/ • MongoDB native Node.js driver docs: http://mongodb.github.io/node-mongodb-native/ 03.03.2014 MongoDB Meetup Dnipropetrovsk 14 /16