使用mongoose可以讓我們更好使用mongodb數(shù)據(jù)庫,而不需要寫繁瑣的業(yè)務(wù)邏輯。
安裝
npm install mongoose
初始化使用
使用mongoose前,需安裝node和mongodb,這里不講node和mongodb的安裝方法。
 var mongoose = require("mongoose"); var Schema = mongoose.Schema; var db = mongoose.connection; mongoose.connect('mongodb://localhost/animal'); db.on('error', console.error); db.once('open', function() {  //這里建立模式和模型 }快速入門
在mongoose中,所有的數(shù)據(jù)都是一種模式,每個模式都映射到mongodb的集合,并且定義該集合文件結(jié)構(gòu)。
 //這里建立一個動物的模式,所有動物都擁有這個模式下的所有屬性 var animalSchema = new Schema({  name: String,  age: Number, });模型是我們從Schema中定義的一種多樣化的構(gòu)造函數(shù),模型的實例可以使用很多操作,所有文檔的創(chuàng)建和檢索都是由模型來處理
 var animalMode = db.model('Animal', animalSchema);模型的實例實質(zhì)是文件,而我們可以很輕松創(chuàng)建、修改這種文件
 var cat = new animalMode({  name: 'catName',  age: '7', //這里依然使用字符串,mongoose會自動轉(zhuǎn)換類型  }); cat.save(function(err, thor) {  if (err) return console.log(err);  console.log(thor); }); //或者可以使用create //cat.create(function(err, thor) { // if (err) return console.log(err); // console.log(thor); //}); //執(zhí)行查找 animalMode.find(function(err, people){  if(err) console.log(err);  console.log(people); }); //查找符合條件數(shù)據(jù) animalMode.findOne({title: 'catName'}, function(err, cat){  if(err) console.log(err);  console.log(cat); });Schema
數(shù)據(jù)類型
這是Schema中所有的數(shù)據(jù)類型,包括mongoose自定的數(shù)據(jù)類型
每種數(shù)據(jù)類型的使用
 var animalMode = mongoose.model('Animal', schema); var cat = new animalMode; cat.name = 'Statue of Liberty'    //String cat.age = '7';        //Number cat.updated = new Date;      //Date cat.binary = new Buffer(0);     //Buffer cat.living = false;       //Boolean cat.mixed = { any: { thing: 'i want' } }; //Mixed     cat._someId = new mongoose.Types.ObjectId; //ObjectId cat.ofString.push("strings!");    //Array其中Mixed是mongoose自定義的一種混合類型,因為Mixed沒有定義具體內(nèi)容,可以用{}來使用,以下2種定義形式等價。
 var animalSchema = new Schema({any: {}}); var animalSchema = new Schema({any: {Schema.Types.Mixed}});自定義方法
可以為Schema綁定方法
 var animalSchema = new Schema({  name: String,  age: Number, }); animalSchema.methods.findSimilarTypes = function (cb) {  return this.model('Animal').find({ name: this.name }, cb); } var animalMode = db.model('Animal', animalSchema); cat.findSimilarTypes(function(err, cat){  if(err) console.log(err);  console.log(cat); });也可以為Schema添加靜態(tài)方法
 animalSchema.statics.findByName = function (name, cb) {  return this.find({ name: new RegExp(name, 'i') }, cb); } var animalMode = db.model('Animal', animalSchema); animalMode.findByName('catName', function (err, animals) {  console.log(animals); });索引
我們可以為mongodb數(shù)據(jù)建立索引,mongodb支持二級索引,為了提高數(shù)據(jù)查找和定位,建立復(fù)合索引是必要的
 var animalSchema = new Schema({  name: String,  age: Number,  tags: { age: [String], index: true } // field level }); animalSchema.index({ name: 1, age: -1 }); // schema level但是這種索引的建立可能導(dǎo)致顯著的性能影響,建議在生產(chǎn)下停止,將設(shè)置模式下的自動索引設(shè)置為false禁止
 animalSchema.set('autoIndex', false); // or new Schema({..}, { autoIndex: false });Model
C
 cat.save(function(err, thor) {  if (err) return console.log(err);  console.log(thor); }); //或者可以使用create cat.create(function(err, thor) {  if (err) return console.log(err);  console.log(thor); });R
//findanimalMode.find(function(err, cat){ if (err) console.log(err); console.log(cat);})//findOneanimalMode.findOne({name: 'catName'}, function(err, cat){ if (err) console.log(err); console.log(cat);})//findByID//與 findOne 相同,但它接收文檔的 _id 作為參數(shù),返回單個文檔。_id //可以是字符串或 ObjectId 對象。animalMode.findById(id, function(err, adventure){ if (err) consoel.log(err); console.log(adventure);});//where//查詢數(shù)據(jù)類型是字符串時,可支持正則animalMode.where('age', '2').exec(function(err, cat){ if (err) console.log(err); console.log(cat);});animalMode .where('age').gte(1).lte(10) .where('name', 'catName') .exec(function(err, cat){  if (err) console.log(err);  console.log(cat); });U
官方文檔提供的更新函數(shù)Model.update
Model.update(conditions, doc, [options], [callback])
animalMode.update({name: 'catName'}, {age: '6'}, {multi : true}, function(err, numberAffected, raw){ if (err) return console.log(err); console.log('The number of updated documents was %d', numberAffected); console.log('The raw response from Mongo was ', raw);});D
animalMode.remove({age: 6}, function(err){ if (err) console.log(err);})其它
//返回文檔數(shù)
animalMode.count({age: 2}, function(err, cat){ if (err) console.log(err); console.log(cat);})新聞熱點
疑難解答