SlideShare une entreprise Scribd logo
1  sur  30
MongoDB and Mongoose 101
Phoenix MongoDB Meetup
November 16, 2013
Will Button @wfbutton
About Me
• DevOps/IT/DBA for myList.com
• Founder of FitMeal.me – Meal Planning
• Extensive background in both development
and ops, specifically in scalability and
sustainability
MongoDB – The 10,000 foot View
SQL to Mongo Terminology
In SQL

In Mongo

• Database

• Database

• Table

• Collection

• Record

• Document
Basic CRUD Operations

Users:

Our dataset:

firstName:{type:String},
lastName:{type:String},
userName:{type:String, unique: true},
password:{type:String},
avatar:{type:String},
position:{type:String}
Basic CRUD Operations

Wills-MacBook-Pro:~ willbutton$ mongo
MongoDB shell version: 2.2.0
connecting to: test
> use myapp
switched to db myapp
>
Basic CRUD Operations
“C” is for Create

> db.users.insert( { firstName: "Will", lastName: "Button", username: "rekibnikufesin", password: "Password", avatar:
"images/will.png", position: "CEO" } )
>
Basic CRUD Operations
“R” is for Read

> db.users.find()
{ "_id" : ObjectId("5282dbceca316975c21907ef"), "firstName" : "Will", "lastName" : "Button", "username" : "rekibnikufesin",
"password" : "Password", "avatar" : "images/will.png", "position" : "CEO" }
> db.users.findOne()
{
"_id" : ObjectId("5282dbceca316975c21907ef"),
"firstName" : "Will",
"lastName" : "Button",
"username" : "rekibnikufesin",
"password" : "Password",
"avatar" : "images/will.png",
"position" : "CEO"
}
> db.users.find( { firstName: "Will" } )
{ "_id" : ObjectId("5282dbceca316975c21907ef"), "firstName" : "Will", "lastName" : "Button", "username" : "rekibnikufesin",
"password" : "Password", "avatar" : "images/will.png", "position" : "CEO" }
>
Basic CRUD Operations
“U” is for Update

> db.users.update( { firstName: "Will", lastName: "Button" }, { $set: { position: "Janitor" } } )
>
> db.users.find()
{ "_id" : ObjectId("5282dbceca316975c21907ef"), "avatar" : "images/will.png", "firstName" : "Will", "lastName" : "Button", "password"
: "Password", "position" : "Janitor", "username" : "rekibnikufesin" }
>

$set is your friend!
Basic CRUD Operations
“D” is for Delete

> db.users.remove( { lastName: "Button" } )
> db.users.count()
0
>
mongoose
• MongoDB object modeling for node.js
Why mongoose?
Let's face it, writing MongoDB validation, casting and business logic boilerplate is a
drag. That's why we wrote Mongoose.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
Mongoose provides a straight-forward, schema-based solution to modeling your
application data and includes built-in type casting, validation, query building, business
logic hooks and more, out of the box.
Go With The Flow:
Collections

Schema

Model

Documents

Documents
Putting it in action:
Use case:
• Build a CRM application using the M.E.A.N. stack
• Using Mongoose, provide basic CRUD operations inside the node stack
Database Schema

Database:
myapp
Collection:
users

Collection:
documents

Collection:
communications

firstName
lastName
username
password
avatar
position

docOwner
docType
dateSaved
description
fileLocation

commType
date
description
followUpDate
contact
Schema
A schema maps to a MongoDB collection and defines the shape of the documents within
that collection

var userSchema = new mongoose.Schema({

firstName:{type:String},
lastName:{type:String},
userName:{type:String, unique: true},
password:{type:String},
avatar:{type:String},
position:{type:String}
})
Models
To use our schema definition, we need to convert our blogSchema into a Model we
can work with

app.db.model('user',userSchema) ;
Documents
Instances of Models are Documents

var user = req.app.db.model('user') ;

Documents have built-in methods:
var query = user.find() ;
query.sort({lastName:'asc'}) ;
query.exec(function(err,data){
if(err){
console.log(err);
res.send(500) ;
}
res.json(data) ;
})
Putting it all together
Open a connection

app.db = mongoose.createConnection('mongodb://localhost/myapp') ;

app.db.on('error', function() {
console.error.bind(console, 'mongoose connection error: ');
});
app.db.once('open', function () {
console.log('mongoose open for business');
});
Badass, Right?

But that only gets us so far.
Let’s explore some of the other features available to us, such as validations,
sub-documents, populations
Queries
var user = req.app.db.model('user') ;

try{
var id = req.params['userId'] ;
user.findOne({_id: id}, 'firstName userName', function(err,data){
console.log('find by id') ;
res.json(data) ;
});
}
catch(e){
console.log(e);
res.send(e) ;
}
var user = req.app.db.model('user');
// console.log(req.body) ;
var newuser = new user(req.body);
newuser.validate(function(error) {
if (error) {
res.json({ error : error });
} else {
delete req.body._id ;
user.findByIdAndUpdate({_id:newuser._id},{$set:req.body},function(err,data){
res.json(data) ;
})
}
});
Validations
Validation is defined in the SchemaType
Validation occurs when a document attempts to be saved, after defaults have been applied
Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well

var user = req.app.db.model('user');
// console.log(req.body) ;
var newuser = new user(req.body);
newuser.validate(function(error) {
if (error) {
res.json({ error : error });
} else {
delete req.body._id ;
user.findByIdAndUpdate({_id:newuser._id},{$set:req.body},function(err,data){
res.json(data) ;
})

}
});

All SchemaTypes have the built in required validator.
Numbers have min and max validators.
Strings have enum and match validators.
Validations
var userSchema = new mongoose.Schema({
firstName:{type:String},
lastName:{type:String},
userName:{type:String, unique: true},
password:{type:String},
avatar:{type:String},
position:{type:String}
})
Sub-Documents
Documents within documents?!?!? What is this witchcraft you speak of???
Sub-documents are documents with their own schema and are elements of a
parent’s document array

• All the same features as normal documents
• Saved when parent document saved
• Errors bubble up to parent callback
Sub-Documents
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]
})

Finding a sub-document
var doc = parent.children.id(id);

Add with standard array methods: push, addToSet, unshift
parent.children.push({ name: 'Liesl' });

Remove by id
var doc = parent.children.id(id).remove();
Population
Allows “joining” data from other collections
var communicationSchema = new mongoose.Schema({
commType:{type:String},
date:{type:Date},
description:{type:String},
followUpDate:{type:Date},
owner:[{type: mongoose.Schema.Types.ObjectId, ref:'user'}]
})

var userSchema = new mongoose.Schema({
firstName:{type:String},
lastName:{type:String},
userName:{type:String, unique: true},
password:{type:String},
avatar:{type:String},
position:{type:String}
})

var Communication= mongoose.model(‟Comm', communicationSchema);
var User= mongoose.model(‟User', userSchema);
Population
var stevie = new User({ _id: 0, firstName: “Stevie”, lastName: “Wonder” })
stevie.save(function (err){
if (err) return handleError(err);
var comm1 = new Communication({
commType: “Phone call”,
description: “I just called to say I love you”,
owner: stevie._id
});
comm1.save(function (err){
if (err) return handleError(err);
});
})

Communication
.findOne({ commType: “Phone call”})
.populate(„owner‟)
.exec(function (err,comm){
if(err) return handleError(err);
console.log(„Call owner is %s‟, communication.owner.firstName);
})
Thank You!
• Questions
• Comments
• More Info

Contenu connexe

Tendances

Clean backends with NestJs
Clean backends with NestJsClean backends with NestJs
Clean backends with NestJsAymene Bennour
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training sessionHrichi Mohamed
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0Mika Koivisto
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMongoDB
 
Building better Node.js applications on MariaDB
Building better Node.js applications on MariaDBBuilding better Node.js applications on MariaDB
Building better Node.js applications on MariaDBMariaDB plc
 

Tendances (20)

NestJS
NestJSNestJS
NestJS
 
Clean backends with NestJs
Clean backends with NestJsClean backends with NestJs
Clean backends with NestJs
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
Benefits of developing single page web applications using angular js
Benefits of developing single page web applications using angular jsBenefits of developing single page web applications using angular js
Benefits of developing single page web applications using angular js
 
Express JS
Express JSExpress JS
Express JS
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Spring boot
Spring bootSpring boot
Spring boot
 
Express js
Express jsExpress js
Express js
 
Building better Node.js applications on MariaDB
Building better Node.js applications on MariaDBBuilding better Node.js applications on MariaDB
Building better Node.js applications on MariaDB
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Express node js
Express node jsExpress node js
Express node js
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 

Similaire à Mongoose and MongoDB 101

Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
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
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB
 
Webinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting StartedWebinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting StartedMongoDB
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBMongoDB
 
MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)Mike Dirolf
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverMongoDB
 
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
 
Sencha Touch - Introduction
Sencha Touch - IntroductionSencha Touch - Introduction
Sencha Touch - IntroductionABC-GROEP.BE
 
Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2MongoDB
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaMongoDB
 
Building HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDBBuilding HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDBdonnfelker
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1Paras Mendiratta
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBLisa Roth, PMP
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 

Similaire à Mongoose and MongoDB 101 (20)

Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
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
 
Node js crash course session 5
Node js crash course   session 5Node js crash course   session 5
Node js crash course session 5
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN Stack
 
Webinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting StartedWebinar: Build an Application Series - Session 2 - Getting Started
Webinar: Build an Application Series - Session 2 - Getting Started
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
 
MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
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
 
Sencha Touch - Introduction
Sencha Touch - IntroductionSencha Touch - Introduction
Sencha Touch - Introduction
 
Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
 
Building HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDBBuilding HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDB
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDBMongoDB .local London 2019: Fast Machine Learning Development with MongoDB
MongoDB .local London 2019: Fast Machine Learning Development with MongoDB
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 

Plus de Will Button

Build an Infra Product with AWS Fargate
Build an Infra Product with AWS FargateBuild an Infra Product with AWS Fargate
Build an Infra Product with AWS FargateWill Button
 
DevOps for Developers
DevOps for DevelopersDevOps for Developers
DevOps for DevelopersWill Button
 
Deploy Nodejs on Docker
Deploy Nodejs on DockerDeploy Nodejs on Docker
Deploy Nodejs on DockerWill Button
 
Effective Telepresence and Remote Collaboration
Effective Telepresence and Remote CollaborationEffective Telepresence and Remote Collaboration
Effective Telepresence and Remote CollaborationWill Button
 
No More Mr. Nice Guy The MEAN Stack
No More Mr. Nice Guy   The MEAN StackNo More Mr. Nice Guy   The MEAN Stack
No More Mr. Nice Guy The MEAN StackWill Button
 
Practical MongoDB
Practical MongoDBPractical MongoDB
Practical MongoDBWill Button
 
Mongo Sharding: Case Study
Mongo Sharding: Case StudyMongo Sharding: Case Study
Mongo Sharding: Case StudyWill Button
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Will Button
 

Plus de Will Button (9)

Build an Infra Product with AWS Fargate
Build an Infra Product with AWS FargateBuild an Infra Product with AWS Fargate
Build an Infra Product with AWS Fargate
 
DevOps for Developers
DevOps for DevelopersDevOps for Developers
DevOps for Developers
 
Deploy Nodejs on Docker
Deploy Nodejs on DockerDeploy Nodejs on Docker
Deploy Nodejs on Docker
 
Effective Telepresence and Remote Collaboration
Effective Telepresence and Remote CollaborationEffective Telepresence and Remote Collaboration
Effective Telepresence and Remote Collaboration
 
Traxticsearch
TraxticsearchTraxticsearch
Traxticsearch
 
No More Mr. Nice Guy The MEAN Stack
No More Mr. Nice Guy   The MEAN StackNo More Mr. Nice Guy   The MEAN Stack
No More Mr. Nice Guy The MEAN Stack
 
Practical MongoDB
Practical MongoDBPractical MongoDB
Practical MongoDB
 
Mongo Sharding: Case Study
Mongo Sharding: Case StudyMongo Sharding: Case Study
Mongo Sharding: Case Study
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07
 

Dernier

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 

Dernier (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 

Mongoose and MongoDB 101

  • 1. MongoDB and Mongoose 101 Phoenix MongoDB Meetup November 16, 2013 Will Button @wfbutton
  • 2. About Me • DevOps/IT/DBA for myList.com • Founder of FitMeal.me – Meal Planning • Extensive background in both development and ops, specifically in scalability and sustainability
  • 3. MongoDB – The 10,000 foot View
  • 4. SQL to Mongo Terminology In SQL In Mongo • Database • Database • Table • Collection • Record • Document
  • 5. Basic CRUD Operations Users: Our dataset: firstName:{type:String}, lastName:{type:String}, userName:{type:String, unique: true}, password:{type:String}, avatar:{type:String}, position:{type:String}
  • 6. Basic CRUD Operations Wills-MacBook-Pro:~ willbutton$ mongo MongoDB shell version: 2.2.0 connecting to: test > use myapp switched to db myapp >
  • 7. Basic CRUD Operations “C” is for Create > db.users.insert( { firstName: "Will", lastName: "Button", username: "rekibnikufesin", password: "Password", avatar: "images/will.png", position: "CEO" } ) >
  • 8. Basic CRUD Operations “R” is for Read > db.users.find() { "_id" : ObjectId("5282dbceca316975c21907ef"), "firstName" : "Will", "lastName" : "Button", "username" : "rekibnikufesin", "password" : "Password", "avatar" : "images/will.png", "position" : "CEO" } > db.users.findOne() { "_id" : ObjectId("5282dbceca316975c21907ef"), "firstName" : "Will", "lastName" : "Button", "username" : "rekibnikufesin", "password" : "Password", "avatar" : "images/will.png", "position" : "CEO" } > db.users.find( { firstName: "Will" } ) { "_id" : ObjectId("5282dbceca316975c21907ef"), "firstName" : "Will", "lastName" : "Button", "username" : "rekibnikufesin", "password" : "Password", "avatar" : "images/will.png", "position" : "CEO" } >
  • 9. Basic CRUD Operations “U” is for Update > db.users.update( { firstName: "Will", lastName: "Button" }, { $set: { position: "Janitor" } } ) > > db.users.find() { "_id" : ObjectId("5282dbceca316975c21907ef"), "avatar" : "images/will.png", "firstName" : "Will", "lastName" : "Button", "password" : "Password", "position" : "Janitor", "username" : "rekibnikufesin" } > $set is your friend!
  • 10. Basic CRUD Operations “D” is for Delete > db.users.remove( { lastName: "Button" } ) > db.users.count() 0 >
  • 11. mongoose • MongoDB object modeling for node.js
  • 12. Why mongoose? Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose. var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var Cat = mongoose.model('Cat', { name: String }); var kitty = new Cat({ name: 'Zildjian' }); kitty.save(function (err) { if (err) // ... console.log('meow'); }); Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
  • 13. Go With The Flow: Collections Schema Model Documents Documents
  • 14. Putting it in action: Use case: • Build a CRM application using the M.E.A.N. stack • Using Mongoose, provide basic CRUD operations inside the node stack
  • 16. Schema A schema maps to a MongoDB collection and defines the shape of the documents within that collection var userSchema = new mongoose.Schema({ firstName:{type:String}, lastName:{type:String}, userName:{type:String, unique: true}, password:{type:String}, avatar:{type:String}, position:{type:String} })
  • 17. Models To use our schema definition, we need to convert our blogSchema into a Model we can work with app.db.model('user',userSchema) ;
  • 18. Documents Instances of Models are Documents var user = req.app.db.model('user') ; Documents have built-in methods: var query = user.find() ; query.sort({lastName:'asc'}) ; query.exec(function(err,data){ if(err){ console.log(err); res.send(500) ; } res.json(data) ; })
  • 19. Putting it all together Open a connection app.db = mongoose.createConnection('mongodb://localhost/myapp') ; app.db.on('error', function() { console.error.bind(console, 'mongoose connection error: '); }); app.db.once('open', function () { console.log('mongoose open for business'); });
  • 20.
  • 21.
  • 22. Badass, Right? But that only gets us so far. Let’s explore some of the other features available to us, such as validations, sub-documents, populations
  • 23. Queries var user = req.app.db.model('user') ; try{ var id = req.params['userId'] ; user.findOne({_id: id}, 'firstName userName', function(err,data){ console.log('find by id') ; res.json(data) ; }); } catch(e){ console.log(e); res.send(e) ; } var user = req.app.db.model('user'); // console.log(req.body) ; var newuser = new user(req.body); newuser.validate(function(error) { if (error) { res.json({ error : error }); } else { delete req.body._id ; user.findByIdAndUpdate({_id:newuser._id},{$set:req.body},function(err,data){ res.json(data) ; }) } });
  • 24. Validations Validation is defined in the SchemaType Validation occurs when a document attempts to be saved, after defaults have been applied Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well var user = req.app.db.model('user'); // console.log(req.body) ; var newuser = new user(req.body); newuser.validate(function(error) { if (error) { res.json({ error : error }); } else { delete req.body._id ; user.findByIdAndUpdate({_id:newuser._id},{$set:req.body},function(err,data){ res.json(data) ; }) } }); All SchemaTypes have the built in required validator. Numbers have min and max validators. Strings have enum and match validators.
  • 25. Validations var userSchema = new mongoose.Schema({ firstName:{type:String}, lastName:{type:String}, userName:{type:String, unique: true}, password:{type:String}, avatar:{type:String}, position:{type:String} })
  • 26. Sub-Documents Documents within documents?!?!? What is this witchcraft you speak of??? Sub-documents are documents with their own schema and are elements of a parent’s document array • All the same features as normal documents • Saved when parent document saved • Errors bubble up to parent callback
  • 27. Sub-Documents var childSchema = new Schema({ name: 'string' }); var parentSchema = new Schema({ children: [childSchema] }) Finding a sub-document var doc = parent.children.id(id); Add with standard array methods: push, addToSet, unshift parent.children.push({ name: 'Liesl' }); Remove by id var doc = parent.children.id(id).remove();
  • 28. Population Allows “joining” data from other collections var communicationSchema = new mongoose.Schema({ commType:{type:String}, date:{type:Date}, description:{type:String}, followUpDate:{type:Date}, owner:[{type: mongoose.Schema.Types.ObjectId, ref:'user'}] }) var userSchema = new mongoose.Schema({ firstName:{type:String}, lastName:{type:String}, userName:{type:String, unique: true}, password:{type:String}, avatar:{type:String}, position:{type:String} }) var Communication= mongoose.model(‟Comm', communicationSchema); var User= mongoose.model(‟User', userSchema);
  • 29. Population var stevie = new User({ _id: 0, firstName: “Stevie”, lastName: “Wonder” }) stevie.save(function (err){ if (err) return handleError(err); var comm1 = new Communication({ commType: “Phone call”, description: “I just called to say I love you”, owner: stevie._id }); comm1.save(function (err){ if (err) return handleError(err); }); }) Communication .findOne({ commType: “Phone call”}) .populate(„owner‟) .exec(function (err,comm){ if(err) return handleError(err); console.log(„Call owner is %s‟, communication.owner.firstName); })
  • 30. Thank You! • Questions • Comments • More Info

Notes de l'éditeur

  1. 20 min to here