// mongoose 鏈接varmongoose=require('mongoose');vardb=mongoose.createConnection('mongodb://127.0.0.1:27017/NodeJS');
// 鏈接錯(cuò)誤db.on('error',function(error){console.log(error);});
// Schema 結(jié)構(gòu)varmongooseSchema=newmongoose.Schema({username:{type:String,default:'匿名用戶'},title:{type:String},content:{type:String},time:{type:Date,default:Date.now},age:{type:Number}});
// 添加 mongoose 實(shí)例方法mongooseSchema.methods.findbyusername=function(username,callback){returnthis.model('mongoose').find({username:username},callback);}
// 添加 mongoose 靜態(tài)方法抓韩,靜態(tài)方法在Model層就能使用mongooseSchema.statics.findbytitle=function(title,callback){returnthis.model('mongoose').find({title:title},callback);}
// modelvarmongooseModel=db.model('mongoose',mongooseSchema);
// 增加記錄 基于 entity 操作vardoc={username:'emtity_demo_username',title:'emtity_demo_title',content:'emtity_demo_content'};varmongooseEntity=newmongooseModel(doc);mongooseEntity.save(function(error){if(error){console.log(error);}else{console.log('saved OK!');}// 關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// 增加記錄 基于model操作vardoc={username:'model_demo_username',title:'model_demo_title',content:'model_demo_content'};mongooseModel.create(doc,function(error){if(error){console.log(error);}else{console.log('save ok');}// 關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// 修改記錄mongooseModel.update(conditions,update,options,callback);varconditions={username:'model_demo_username'};varupdate={$set:{age:27,title:'model_demo_title_update'}};varoptions={upsert:true};mongooseModel.update(conditions,update,options,function(error){if(error){console.log(error);}else{console.log('update ok!');}//關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// 查詢// 基于實(shí)例方法的查詢varmongooseEntity=newmongooseModel({});mongooseEntity.findbyusername('model_demo_username',function(error,result){if(error){console.log(error);}else{console.log(result);}//關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// 基于靜態(tài)方法的查詢mongooseModel.findbytitle('emtity_demo_title',function(error,result){if(error){console.log(error);}else{console.log(result);}//關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// mongoose findvarcriteria={title:'emtity_demo_title'};// 查詢條件varfields={title:1,content:1,time:1};// 待返回的字段varoptions={};mongooseModel.find(criteria,fields,options,function(error,result){if(error){console.log(error);}else{console.log(result);}//關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});
// 刪除記錄varconditions={username:'emtity_demo_username'};mongooseModel.remove(conditions,function(error){if(error){console.log(error);}else{console.log('delete ok!');}//關(guān)閉數(shù)據(jù)庫(kù)鏈接db.close();});