SlideShare a Scribd company logo
1 of 16
Download to read offline
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

More Related Content

What's hot

Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Eric Bourdet
 
Connexion jdbc
Connexion jdbcConnexion jdbc
Connexion jdbcInes Ouaz
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMongoDB
 
[부스트캠퍼세미나]김재원_presentation-oop
[부스트캠퍼세미나]김재원_presentation-oop[부스트캠퍼세미나]김재원_presentation-oop
[부스트캠퍼세미나]김재원_presentation-oopCONNECT FOUNDATION
 
Aem sling resolution
Aem sling resolutionAem sling resolution
Aem sling resolutionGaurav Tiwari
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Angular Framework présentation PPT LIGHT
Angular Framework présentation PPT LIGHTAngular Framework présentation PPT LIGHT
Angular Framework présentation PPT LIGHTtayebbousfiha1
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les basesAntoine Rey
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 
RESTful API 설계
RESTful API 설계RESTful API 설계
RESTful API 설계Jinho Yoo
 

What's hot (20)

Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01
 
Connexion jdbc
Connexion jdbcConnexion jdbc
Connexion jdbc
 
Introduction à Laravel
Introduction à LaravelIntroduction à Laravel
Introduction à Laravel
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
[부스트캠퍼세미나]김재원_presentation-oop
[부스트캠퍼세미나]김재원_presentation-oop[부스트캠퍼세미나]김재원_presentation-oop
[부스트캠퍼세미나]김재원_presentation-oop
 
Aem sling resolution
Aem sling resolutionAem sling resolution
Aem sling resolution
 
Angular Avancé
Angular AvancéAngular Avancé
Angular Avancé
 
Express JS
Express JSExpress JS
Express JS
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Angular Framework présentation PPT LIGHT
Angular Framework présentation PPT LIGHTAngular Framework présentation PPT LIGHT
Angular Framework présentation PPT LIGHT
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Angular.pdf
Angular.pdfAngular.pdf
Angular.pdf
 
Introduction à Angular
Introduction à AngularIntroduction à Angular
Introduction à Angular
 
Introduction à Node.js
Introduction à Node.js Introduction à Node.js
Introduction à Node.js
 
RESTful API 설계
RESTful API 설계RESTful API 설계
RESTful API 설계
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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