SlideShare a Scribd company logo
1 of 16
Download to read offline
mongoose
using mongoDB with node.js
mongoose
• mongo資料庫物件操作 for node.js
• 定義schema
• middleware
• 操作model
• validation
• 類join: population
• ⽂文件操作
mongoose
• mongo資料庫物件操作 for node.js
• connect(uri, option, callback)
安裝
$	
  npm	
  install	
  mongoose
var	
  mongoose	
  =	
  require('mongoose');
var	
  cb	
  =	
  function(err)	
  {
	
  	
  if	
  (err)	
  {
	
  	
  	
  	
  return	
  console.log("Error	
  connecting	
  to:	
  "	
  +	
  uristring	
  +	
  ".");
	
  	
  }	
  else	
  {
	
  	
  	
  	
  return	
  console.log("Successfully	
  connected	
  to:	
  "	
  +	
  uristring);
	
  	
  }
});
mongoose.connect('mongodb://localhost/test',	
  {db:	
  {safe:true}},	
  cb);
Schemas
var	
  blogSchema	
  =	
  new	
  Schema({
	
  	
  title:	
  	
  {	
  type:	
  String,	
  index:	
  true	
  },
	
  	
  author:	
  String,
	
  	
  body:	
  	
  	
  String,
	
  	
  comments:	
  [{	
  body:	
  String,	
  date:	
  Date	
  }],
	
  	
  date:	
  {	
  type:	
  Date,	
  default:	
  Date.now	
  },
	
  	
  hidden:	
  Boolean,
	
  	
  meta:	
  {
	
  	
  	
  	
  votes:	
  Number,
	
  	
  	
  	
  favs:	
  	
  Number
	
  	
  }
});
Schemas
• Types
• String
• Number
• Date
• Buffer
• Boolean
• Mixed
• Objectid
• Array
Schemas
var	
  schema	
  =	
  new	
  Schema({
	
  	
  name:	
  	
  	
  	
  String,
	
  	
  binary:	
  	
  Buffer,
	
  	
  living:	
  	
  Boolean,
	
  	
  updated:	
  {	
  type:	
  Date,	
  default:	
  Date.now	
  }
	
  	
  age:	
  	
  	
  	
  	
  {	
  type:	
  Number,	
  min:	
  18,	
  max:	
  65	
  }
	
  	
  mixed:	
  	
  	
  Schema.Types.Mixed,
	
  	
  _someId:	
  Schema.Types.ObjectId,
	
  	
  array:	
  	
  	
  	
  	
  	
  [],
	
  	
  ofString:	
  	
  	
  [String],
	
  	
  ofNumber:	
  	
  	
  [Number],
	
  	
  ofDates:	
  	
  	
  	
  [Date],
	
  	
  ofBuffer:	
  	
  	
  [Buffer],
	
  	
  ofBoolean:	
  	
  [Boolean],
	
  	
  ofMixed:	
  	
  	
  	
  [Schema.Types.Mixed],
	
  	
  ofObjectId:	
  [Schema.Types.ObjectId],
	
  	
  nested:	
  {
	
  	
  	
  	
  stuff:	
  {	
  type:	
  String,	
  lowercase:	
  true,	
  trim:	
  true	
  }
	
  	
  }
})
Schemas
//	
  example	
  use
var	
  Thing	
  =	
  mongoose.model('Thing',	
  schema);
var	
  m	
  =	
  new	
  Thing();
m.name	
  =	
  'Statue	
  of	
  Liberty'
m.age	
  =	
  125;
m.updated	
  =	
  new	
  Date;
m.binary	
  =	
  new	
  Buffer(0);
m.living	
  =	
  false;
m.mixed	
  =	
  {[	
  any:	
  {	
  thing:	
  'i	
  want'	
  }	
  ]};
m.markModified('mixed');
m._someId	
  =	
  new	
  mongoose.Types.ObjectId();
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDate.addToSet(new	
  Date());
m.ofBuffer.pop();
m.ofMixed	
  =	
  [1,	
  [],	
  'three',	
  {	
  four:	
  5	
  }];
m.nested.stuff	
  =	
  'good';
m.save(callback);
Schemas
userSchema.methods.comparePassword	
  =	
  function(candidatePassword,	
  cb)	
  {
	
  	
  if	
  (	
  candidatePassword	
  ==	
  this.password	
  )	
  {
	
  	
  	
  	
  return	
  cb(null,	
  true);
	
  	
  }	
  else	
  {
	
  	
  	
  	
  return	
  cb(	
  new	
  Error("Password	
  does	
  not	
  match")	
  );
	
  	
  }
};
userSchema.statics.findByName	
  =	
  function(name,	
  cb)	
  {
	
  	
  this.find({	
  name:	
  name	
  },	
  cb);
};
personSchema.virtual('name.full').get(function	
  ()	
  {
	
  	
  return	
  this.name.first	
  +	
  '	
  '	
  +	
  this.name.last;
});
middleware
userSchema.pre('save',	
  function(next)	
  {
	
  	
  //encrypt	
  password	
  and	
  save	
  to	
  password	
  field
});
init, validate, save, remove前後執⾏行
userSchema.post('save',	
  function	
  (user)	
  {
	
  	
  console.log('%s	
  has	
  been	
  saved',	
  user._id);
})
內建validator
ALL: required
Numbers: min, max
Strings: enum
Validation
courseSchema	
  =	
  new	
  Schema({
	
  	
  title:	
  {
	
  	
  	
  	
  type:	
  String,
	
  	
  	
  	
  required:	
  true
	
  	
  },
	
  	
  description:	
  String,
	
  	
  status:	
  {
	
  	
  	
  	
  type:	
  String,
	
  	
  	
  	
  "enum":	
  ['on',	
  'off']
	
  	
  }
});
⾃自定Validator
var	
  toySchema	
  =	
  new	
  Schema({
	
  	
  color:	
  String,
	
  	
  name:	
  String
});
var	
  Toy	
  =	
  mongoose.model('Toy',	
  toySchema);
Toy.schema.path('color').validate(function	
  (value)	
  {
	
  	
  return	
  /blue|green|white|red|orange|periwinkel/i.test(value);
},	
  'Invalid	
  color');
var	
  toy	
  =	
  new	
  Toy({	
  color:	
  'grease'});
toy.save(function	
  (err)	
  {
	
  	
  //	
  err.errors.color	
  is	
  a	
  ValidatorError	
  object
	
  	
  
	
  	
  console.log(err.errors.color.message)	
  //	
  prints	
  'Validator	
  "Invalid	
  color"	
  
failed	
  for	
  path	
  color	
  with	
  value	
  `grease`'
	
  	
  console.log(String(err.errors.color))	
  //	
  prints	
  'Validator	
  "Invalid	
  color"	
  
failed	
  for	
  path	
  color	
  with	
  value	
  `grease`'
	
  	
  console.log(err.errors.color.type)	
  	
  //	
  prints	
  "Invalid	
  color"
	
  	
  console.log(err.errors.color.path)	
  	
  //	
  prints	
  "color"
	
  	
  console.log(err.errors.color.value)	
  //	
  prints	
  "grease"
	
  	
  console.log(err.name)	
  //	
  prints	
  "ValidationError"
	
  	
  console.log(err.message)	
  //	
  prints	
  "Validation	
  failed"
});
population
var	
  mongoose	
  =	
  require('mongoose')
	
  	
  ,	
  Schema	
  =	
  mongoose.Schema
	
  	
  
var	
  personSchema	
  =	
  Schema({
	
  	
  _id	
  	
  	
  	
  	
  :	
  Number,
	
  	
  name	
  	
  	
  	
  :	
  String,
	
  	
  age	
  	
  	
  	
  	
  :	
  Number,
	
  	
  stories	
  :	
  [{	
  type:	
  Schema.Types.ObjectId,	
  ref:	
  'Story'	
  }]
});
var	
  storySchema	
  =	
  Schema({
	
  	
  _creator	
  :	
  {	
  type:	
  Number,	
  ref:	
  'Person'	
  },
	
  	
  title	
  	
  	
  	
  :	
  String,
	
  	
  fans	
  	
  	
  	
  	
  :	
  [{	
  type:	
  Number,	
  ref:	
  'Person'	
  }]
});
var	
  Story	
  	
  =	
  mongoose.model('Story',	
  storySchema);
var	
  Person	
  =	
  mongoose.model('Person',	
  personSchema);
類似join的功能
類似foreign key
也可以有多筆foreign key
population
Story
.findOne({	
  title:	
  /timex/i	
  })
.populate('_creator',	
  'name')	
  //	
  only	
  return	
  the	
  Persons	
  name
.exec(function	
  (err,	
  story)	
  {
	
  	
  if	
  (err)	
  return	
  handleError(err);
	
  	
  
	
  	
  console.log('The	
  creator	
  is	
  %s',	
  story._creator.name);
	
  	
  //	
  prints	
  "The	
  creator	
  is	
  Aaron"
	
  	
  
	
  	
  console.log('The	
  creators	
  age	
  is	
  %s',	
  story._creator.age);
	
  	
  //	
  prints	
  "The	
  creators	
  age	
  is	
  null'
})
Models 新增資料
var	
  schema	
  =	
  new	
  mongoose.Schema({	
  name:	
  'string',	
  size:	
  'string'	
  })
var	
  Tank	
  =	
  mongoose.model('Tank',	
  schema);
var	
  Tank	
  =	
  mongoose.model('Tank');
var	
  small	
  =	
  new	
  Tank({	
  name:	
  'T92',	
  type:	
  'light'	
  });
small.save(function	
  (err)	
  {
	
  	
  if	
  (err)	
  return	
  handleError(err);
	
  	
  //	
  saved!
})
//	
  or
Tank.create({	
  name:	
  'M1A1',	
  type:	
  'MBT'	
  },	
  function	
  (err,	
  small)	
  {
	
  	
  if	
  (err)	
  return	
  handleError(err);
	
  	
  //	
  saved!
})
Models 操作
var	
  schema	
  =	
  new	
  mongoose.Schema({	
  name:	
  'string',	
  size:	
  'string'	
  })
var	
  Tank	
  =	
  mongoose.model('Tank',	
  schema);
User.find({age:	
  {$gte:	
  21,	
  $lte:	
  65}},	
  callback);
User.where('age').gte(21).lte(65).exec(callback);
Tank.remove({	
  type:	
  'light'	
  },	
  function	
  (err)	
  {
	
  	
  if	
  (err)	
  return	
  handleError(err);
	
  	
  //	
  removed!
});
Models 操作
Tank.findByIdAndUpdate(id,	
  {	
  $set:	
  {	
  size:	
  'MBT'	
  }},	
  function	
  (err,	
  
tank)	
  {
	
  	
  if	
  (err)	
  return	
  handleError(err);
	
  	
  res.send(tank);	
  	
  //return	
  updated	
  document
});
var	
  query	
  =	
  {	
  name:	
  'borne'	
  };
Model.update(query,	
  {	
  name:	
  'jason	
  borne'	
  },	
  options,	
  callback)
//	
  is	
  sent	
  as
Model.update(query,	
  {	
  $set:	
  {	
  name:	
  'jason	
  borne'	
  }},	
  options,	
  
callback)

More Related Content

What's hot

Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integraçãoVinícius Pretto da Silva
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB ShellMongoDB
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며지수 윤
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJsHenri Binsztok
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...Walter Dal Mut
 
How to build microservices with node.js
How to build microservices with node.jsHow to build microservices with node.js
How to build microservices with node.jsKaty Slemon
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6Andy Sharman
 
[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...Functional Thursday
 
jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDbsliimohara
 
Format xls sheets Demo Mode
Format xls sheets Demo ModeFormat xls sheets Demo Mode
Format xls sheets Demo ModeJared Bourne
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryWingify Engineering
 

What's hot (17)

Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Mongo db for C# Developers
Mongo db for C# DevelopersMongo db for C# Developers
Mongo db for C# Developers
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB Shell
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJs
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
 
How to build microservices with node.js
How to build microservices with node.jsHow to build microservices with node.js
How to build microservices with node.js
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6
 
[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...
 
jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDb
 
Format xls sheets Demo Mode
Format xls sheets Demo ModeFormat xls sheets Demo Mode
Format xls sheets Demo Mode
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQuery
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
 

Viewers also liked

Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2Ynon Perek
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseYnon Perek
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichAWS Germany
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Brightaaronheckmann
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in InsuranceCognizant
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM CapabilitiesArlene DeMita
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer ExperienceCognizant
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structureSOuvagya Kumar Jena
 

Viewers also liked (12)

Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and Mongoose
 
Express JS
Express JSExpress JS
Express JS
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science Bereich
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Bright
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM Capabilities
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structure
 
Express js
Express jsExpress js
Express js
 

Similar to Nodejs mongoose

What the web platform (and your app!) can learn from Node.js
What the web platform (and your app!) can learn from Node.jsWhat the web platform (and your app!) can learn from Node.js
What the web platform (and your app!) can learn from Node.jswbinnssmith
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
 
js+ts fullstack typescript with react and express.pdf
js+ts fullstack typescript with react and express.pdfjs+ts fullstack typescript with react and express.pdf
js+ts fullstack typescript with react and express.pdfNuttavutThongjor1
 
fullstack typescript with react and express.pdf
fullstack typescript with react and express.pdffullstack typescript with react and express.pdf
fullstack typescript with react and express.pdfNuttavutThongjor1
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!Guilherme Carreiro
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptShah Jalal
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by HowardLearningTech
 
Howard type script
Howard   type scriptHoward   type script
Howard type scriptLearningTech
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 

Similar to Nodejs mongoose (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
typeorm.pdf
typeorm.pdftypeorm.pdf
typeorm.pdf
 
What the web platform (and your app!) can learn from Node.js
What the web platform (and your app!) can learn from Node.jsWhat the web platform (and your app!) can learn from Node.js
What the web platform (and your app!) can learn from Node.js
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
ts+js
ts+jsts+js
ts+js
 
js+ts fullstack typescript with react and express.pdf
js+ts fullstack typescript with react and express.pdfjs+ts fullstack typescript with react and express.pdf
js+ts fullstack typescript with react and express.pdf
 
fullstack typescript with react and express.pdf
fullstack typescript with react and express.pdffullstack typescript with react and express.pdf
fullstack typescript with react and express.pdf
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
 
Js hacks
Js hacksJs hacks
Js hacks
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
 
Howard type script
Howard   type scriptHoward   type script
Howard type script
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
MongoDB and RDBMS
MongoDB and RDBMSMongoDB and RDBMS
MongoDB and RDBMS
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Nodejs mongoose

  • 2. mongoose • mongo資料庫物件操作 for node.js • 定義schema • middleware • 操作model • validation • 類join: population • ⽂文件操作
  • 3. mongoose • mongo資料庫物件操作 for node.js • connect(uri, option, callback) 安裝 $  npm  install  mongoose var  mongoose  =  require('mongoose'); var  cb  =  function(err)  {    if  (err)  {        return  console.log("Error  connecting  to:  "  +  uristring  +  ".");    }  else  {        return  console.log("Successfully  connected  to:  "  +  uristring);    } }); mongoose.connect('mongodb://localhost/test',  {db:  {safe:true}},  cb);
  • 4. Schemas var  blogSchema  =  new  Schema({    title:    {  type:  String,  index:  true  },    author:  String,    body:      String,    comments:  [{  body:  String,  date:  Date  }],    date:  {  type:  Date,  default:  Date.now  },    hidden:  Boolean,    meta:  {        votes:  Number,        favs:    Number    } });
  • 5. Schemas • Types • String • Number • Date • Buffer • Boolean • Mixed • Objectid • Array
  • 6. Schemas var  schema  =  new  Schema({    name:        String,    binary:    Buffer,    living:    Boolean,    updated:  {  type:  Date,  default:  Date.now  }    age:          {  type:  Number,  min:  18,  max:  65  }    mixed:      Schema.Types.Mixed,    _someId:  Schema.Types.ObjectId,    array:            [],    ofString:      [String],    ofNumber:      [Number],    ofDates:        [Date],    ofBuffer:      [Buffer],    ofBoolean:    [Boolean],    ofMixed:        [Schema.Types.Mixed],    ofObjectId:  [Schema.Types.ObjectId],    nested:  {        stuff:  {  type:  String,  lowercase:  true,  trim:  true  }    } })
  • 7. Schemas //  example  use var  Thing  =  mongoose.model('Thing',  schema); var  m  =  new  Thing(); m.name  =  'Statue  of  Liberty' m.age  =  125; m.updated  =  new  Date; m.binary  =  new  Buffer(0); m.living  =  false; m.mixed  =  {[  any:  {  thing:  'i  want'  }  ]}; m.markModified('mixed'); m._someId  =  new  mongoose.Types.ObjectId(); m.array.push(1); m.ofString.push("strings!"); m.ofNumber.unshift(1,2,3,4); m.ofDate.addToSet(new  Date()); m.ofBuffer.pop(); m.ofMixed  =  [1,  [],  'three',  {  four:  5  }]; m.nested.stuff  =  'good'; m.save(callback);
  • 8. Schemas userSchema.methods.comparePassword  =  function(candidatePassword,  cb)  {    if  (  candidatePassword  ==  this.password  )  {        return  cb(null,  true);    }  else  {        return  cb(  new  Error("Password  does  not  match")  );    } }; userSchema.statics.findByName  =  function(name,  cb)  {    this.find({  name:  name  },  cb); }; personSchema.virtual('name.full').get(function  ()  {    return  this.name.first  +  '  '  +  this.name.last; });
  • 9. middleware userSchema.pre('save',  function(next)  {    //encrypt  password  and  save  to  password  field }); init, validate, save, remove前後執⾏行 userSchema.post('save',  function  (user)  {    console.log('%s  has  been  saved',  user._id); })
  • 10. 內建validator ALL: required Numbers: min, max Strings: enum Validation courseSchema  =  new  Schema({    title:  {        type:  String,        required:  true    },    description:  String,    status:  {        type:  String,        "enum":  ['on',  'off']    } });
  • 11. ⾃自定Validator var  toySchema  =  new  Schema({    color:  String,    name:  String }); var  Toy  =  mongoose.model('Toy',  toySchema); Toy.schema.path('color').validate(function  (value)  {    return  /blue|green|white|red|orange|periwinkel/i.test(value); },  'Invalid  color'); var  toy  =  new  Toy({  color:  'grease'}); toy.save(function  (err)  {    //  err.errors.color  is  a  ValidatorError  object        console.log(err.errors.color.message)  //  prints  'Validator  "Invalid  color"   failed  for  path  color  with  value  `grease`'    console.log(String(err.errors.color))  //  prints  'Validator  "Invalid  color"   failed  for  path  color  with  value  `grease`'    console.log(err.errors.color.type)    //  prints  "Invalid  color"    console.log(err.errors.color.path)    //  prints  "color"    console.log(err.errors.color.value)  //  prints  "grease"    console.log(err.name)  //  prints  "ValidationError"    console.log(err.message)  //  prints  "Validation  failed" });
  • 12. population var  mongoose  =  require('mongoose')    ,  Schema  =  mongoose.Schema     var  personSchema  =  Schema({    _id          :  Number,    name        :  String,    age          :  Number,    stories  :  [{  type:  Schema.Types.ObjectId,  ref:  'Story'  }] }); var  storySchema  =  Schema({    _creator  :  {  type:  Number,  ref:  'Person'  },    title        :  String,    fans          :  [{  type:  Number,  ref:  'Person'  }] }); var  Story    =  mongoose.model('Story',  storySchema); var  Person  =  mongoose.model('Person',  personSchema); 類似join的功能 類似foreign key 也可以有多筆foreign key
  • 13. population Story .findOne({  title:  /timex/i  }) .populate('_creator',  'name')  //  only  return  the  Persons  name .exec(function  (err,  story)  {    if  (err)  return  handleError(err);        console.log('The  creator  is  %s',  story._creator.name);    //  prints  "The  creator  is  Aaron"        console.log('The  creators  age  is  %s',  story._creator.age);    //  prints  "The  creators  age  is  null' })
  • 14. Models 新增資料 var  schema  =  new  mongoose.Schema({  name:  'string',  size:  'string'  }) var  Tank  =  mongoose.model('Tank',  schema); var  Tank  =  mongoose.model('Tank'); var  small  =  new  Tank({  name:  'T92',  type:  'light'  }); small.save(function  (err)  {    if  (err)  return  handleError(err);    //  saved! }) //  or Tank.create({  name:  'M1A1',  type:  'MBT'  },  function  (err,  small)  {    if  (err)  return  handleError(err);    //  saved! })
  • 15. Models 操作 var  schema  =  new  mongoose.Schema({  name:  'string',  size:  'string'  }) var  Tank  =  mongoose.model('Tank',  schema); User.find({age:  {$gte:  21,  $lte:  65}},  callback); User.where('age').gte(21).lte(65).exec(callback); Tank.remove({  type:  'light'  },  function  (err)  {    if  (err)  return  handleError(err);    //  removed! });
  • 16. Models 操作 Tank.findByIdAndUpdate(id,  {  $set:  {  size:  'MBT'  }},  function  (err,   tank)  {    if  (err)  return  handleError(err);    res.send(tank);    //return  updated  document }); var  query  =  {  name:  'borne'  }; Model.update(query,  {  name:  'jason  borne'  },  options,  callback) //  is  sent  as Model.update(query,  {  $set:  {  name:  'jason  borne'  }},  options,   callback)