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

DOCX
Mongoose getting started-Mongo Db with Node js
PPTX
Mongoose and MongoDB 101
PDF
Mongoose: MongoDB object modelling for Node.js
KEY
Practical Use of MongoDB for Node.js
PDF
7주 JavaScript 실습
KEY
CouchDB on Android
PDF
droidQuery: The Android port of jQuery
KEY
MongoDB
Mongoose getting started-Mongo Db with Node js
Mongoose and MongoDB 101
Mongoose: MongoDB object modelling for Node.js
Practical Use of MongoDB for Node.js
7주 JavaScript 실습
CouchDB on Android
droidQuery: The Android port of jQuery
MongoDB

What's hot (17)

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

Viewers also liked (12)

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

Similar to Nodejs mongoose (20)

PDF
MongoDB and its usage
KEY
The Ruby/mongoDB ecosystem
PDF
MongoDB.pdf
PDF
2013-03-23 - NoSQL Spartakiade
PDF
Mongo DB schema design patterns
PDF
10gen Presents Schema Design and Data Modeling
PDF
Mongo db
KEY
Schema Design with MongoDB
KEY
Schema design
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
KEY
MongoDB, PHP and the cloud - php cloud summit 2011
PPTX
mongoyeieheheieueheheueuehwwuwuuuwuwh.pptx
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
ODP
Mongokit presentation mongofr-2010
PPTX
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PDF
FrozenRails Training
PDF
mongodb-introduction
KEY
PostgreSQLからMongoDBへ
PDF
REST Web API with MongoDB
MongoDB and its usage
The Ruby/mongoDB ecosystem
MongoDB.pdf
2013-03-23 - NoSQL Spartakiade
Mongo DB schema design patterns
10gen Presents Schema Design and Data Modeling
Mongo db
Schema Design with MongoDB
Schema design
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
MongoDB, PHP and the cloud - php cloud summit 2011
mongoyeieheheieueheheueuehwwuwuuuwuwh.pptx
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Mongokit presentation mongofr-2010
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Dev Jumpstart: Build Your First App with MongoDB
FrozenRails Training
mongodb-introduction
PostgreSQLからMongoDBへ
REST Web API with MongoDB

Recently uploaded (20)

PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectral efficient network and resource selection model in 5G networks
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
The Rise and Fall of 3GPP – Time for a Sabbatical?
20250228 LYD VKU AI Blended-Learning.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Weekly Chronicles - August'25 Week I
sap open course for s4hana steps from ECC to s4
Digital-Transformation-Roadmap-for-Companies.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
Programs and apps: productivity, graphics, security and other tools

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)