SlideShare a Scribd company logo
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

An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
Pagepro
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
Takakiyo Tanaka
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
Brian Hong
 
MongoDB
MongoDBMongoDB
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Alphorm.com-Formation MongoDB Administration
Alphorm.com-Formation MongoDB AdministrationAlphorm.com-Formation MongoDB Administration
Alphorm.com-Formation MongoDB Administration
Alphorm
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
Jaya Naresh Kovela
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptx
Surya937648
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
DaeMyung Kang
 
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
XpressEngine
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
Hyphen Call
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Microservices avec Spring Cloud
Microservices avec Spring CloudMicroservices avec Spring Cloud
Microservices avec Spring Cloud
Florian Beaufumé
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 

What's hot (20)

An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
IBMが新しいJava EEコンテナを作っているらしい -Libertyプロファイルとは-
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
 
MongoDB
MongoDBMongoDB
MongoDB
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
MongoDB
MongoDBMongoDB
MongoDB
 
Alphorm.com-Formation MongoDB Administration
Alphorm.com-Formation MongoDB AdministrationAlphorm.com-Formation MongoDB Administration
Alphorm.com-Formation MongoDB Administration
 
Express JS
Express JSExpress JS
Express JS
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptx
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
[XECon2016] A-4 조정현 GitHub + Jenkins + Docker로 자동배포 시스템 구축하기
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Microservices avec Spring Cloud
Microservices avec Spring CloudMicroservices avec Spring Cloud
Microservices avec Spring Cloud
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 

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.js
Yoann 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 Studios
Learnimtactics
 
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
MongoDB
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
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
Xebia Nederland BV
 
AngularJS
AngularJSAngularJS
AngularJS
Pasi Manninen
 
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
Francois Zaninotto
 
A Story about AngularJS modularization development
A Story about AngularJS modularization developmentA Story about AngularJS modularization development
A Story about AngularJS modularization development
Johannes 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.pdf
ArthyR3
 
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
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
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
MongoDB
 
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 Developers
cacois
 
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
Richard 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

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 

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