SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesNATS
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Docker: From Zero to Hero
Docker: From Zero to HeroDocker: From Zero to Hero
Docker: From Zero to Herofazalraja
 
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...Simplilearn
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
Learning Docker from Square One
Learning Docker from Square OneLearning Docker from Square One
Learning Docker from Square OneDocker, Inc.
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in phpLeonardo Proietti
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 

Tendances (20)

Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
13 mongoose
13 mongoose13 mongoose
13 mongoose
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices Architectures
 
Express js
Express jsExpress js
Express js
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Docker: From Zero to Hero
Docker: From Zero to HeroDocker: From Zero to Hero
Docker: From Zero to Hero
 
NestJS
NestJSNestJS
NestJS
 
Docker swarm
Docker swarmDocker swarm
Docker swarm
 
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...
Docker Tutorial For Beginners | What Is Docker And How It Works? | Docker Tut...
 
Vue.js
Vue.jsVue.js
Vue.js
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Learning Docker from Square One
Learning Docker from Square OneLearning Docker from Square One
Learning Docker from Square One
 
Spring boot
Spring bootSpring boot
Spring boot
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in php
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 

Similaire à 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
 

Similaire à 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
 

Dernier

[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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Dernier (20)

[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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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