【mongo】mongoose

16720 ワード

mongoose
api:hhttp://mongoosejs.com/docs/ap...
インストールと参照
インストールnpm install mongoose
mongoseを引用var mongoose = require(“mongoose”);
mongoseリンクデータベースの使用
api mongoose.connect('mongodb://username:password@host:port/database?options...');
test mongoose.connect('mongodb://localhost/myapp');
var mongoose = require(“mongoose”); 
var db = mongoose.connect(“mongodb://127.0.0.1:27017/test”); 
db.connection.on(“error”, function (error) { 
console.log(“       :” + error); 
}); 
db.connection.on(“open”, function () { 
console.log(“——       !——”); 
});

MongoDBベース
Schema:ファイル形式で格納されたデータベースモデルのスケルトンで、データベースの操作能力を備えていない
Model:Schemaパブリケーションによって生成されたモデルで、抽象的な属性と動作を持つデータベース操作ペア
Entity:Modelによって作成されたエンティティの操作もデータベースに影響します.
Schema
ファイル形式で格納されたデータベースモデルのスケルトンで、データベース側に直接接続できない、つまりデータベースに対する操作能力を備えていない.データ属性モデル(従来の意味のテーブル構造)、あるいは「集合」のモデルスケルトンと言える.
/*      Schema */
var mongoose = require("mongoose");

var TestSchema = new mongoose.Schema({
    name : { type:String },//  name,   String
    age  : { type:Number, default:0 },//  age,   Number,   0
    time : { type:Date, default:Date.now },
    email: { type:String,default:''}
});

上のTestSchemaは4つの属性[name,age,time,email]を含む
基本プロパティのタイプは、文字列、日付型、数値型、ブール型、null、配列、埋め込みドキュメントなどです.
api
Schema.prototype.clone()
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '    '},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
var cloneSchema = mongooseSchema.clone();

Schema.prototype.add()
var ToySchema = new mongoose.Schema;
ToySchema.add({ name: 'string', color: 'string', price: 'number' });

Schema.prototype.path()
schema.path('name') // returns a SchemaType
schema.path('name', Number) // changes the schemaType of `name` to Number
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '    '},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
console.log(mongooseSchema.path('time'));
  :
SchemaDate {
  path: 'time',
  instance: 'Date',
  validators: [],
  setters: [],
  getters: [],
  options: { type: [Function: Date], default: [Function: now] },
  _index: null,
  defaultValue: [Function: now] }

ミドルウェアapi
参照ドキュメント:https://www.cnblogs.com/surah...
Schema.prototype.pre()
pre hook、シリアル(seria)、パラレル(parallel)の2種類があります.
Serial
シリアルミドルウェアは次々と実行され、各ミドルウェアはnextを呼び出す.
var schema = new Schema(..);
schema.pre('save', function(next) {
  //     
  next();
});

Parallel
パラレルミドルウェアは、より微細な操作を提供します.
var schema = new Schema(..);

// 'true'           .             ,     true        
schema.pre('save', true, function(next, done) {
  //               
  next();
  setTimeout(done, 100);
});

Schema.prototype.post()
Postミドルウェア
postミドルウェアはhookedメソッドとそのpreミドルウェアがすべて完了した後に実行されます.postミドルウェアは、nextおよびdoneコールバックがないなど、ストリーム制御を直接受信しない.post hookは、これらの方法のために従来のイベントリスナーを登録することができる.
schema.post('init', function(doc) {
  console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
  console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
  console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});

Schema.prototype.method()
追加方法
 Schema.methods.say = function(){console.log(‘hello’);};
//    ,    Model     

≪インスタンス|Instance|emdw≫
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '    '},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
//    mongoose     
mongooseSchema.methods.findbyusername = function(username, callback) {
  return this.model('mongoose').find({username: username}, callback);
}
var mongooseModel = db.model('mongoose', mongooseSchema);
var mongooseEntity = new mongooseModel();
mongooseEntity.findbyusername('model_demo_username', function(error, result){
          if(error) {
              console.log(error);
          } else {
              console.log(result);
          }
          //       
          db.close();
      });

パブリックメソッド
これでModelとEntityのインスタンスがこの方法を使用できるようになりました
mongooseSchema.method('meow', function () {
  console.log('meeeeeoooooooooooow');
})

var Kitty = db.model('Kitty', mongooseSchema);

var fizz = new Kitty;
fizz.meow(); 
schema.method({
    purr: function () {}
  , scratch: function () {}
});

// later
fizz.purr();
fizz.scratch();

Schema.prototype.static()
スタティックメソッドは、Model層のみで使用できます
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '    '},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
//    mongoose     ,     Model     
mongooseSchema.statics.findbytitle = function(title, callback) {
  return this.model('mongoose').find({title: title}, callback);
}
var mongooseModel = db.model('mongoose', mongooseSchema);

mongooseModel.findbytitle('emtity_demo_title',function(err,res){})

model
参照ドキュメント:http://www.cnblogs.com/surahe...Schemaによって構築されたモデルは、Schemaによって定義されたデータベース・スケルトンに加えて、データベース・プロパティ、動作を管理するクラスのようなデータベース・アクションの動作を持つ.
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");

//   Model
var TestModel = db.model("test1", TestSchema);
test1          ,       .

Modelの作成
db.model(“test1”, TestSchema );
1.コンストラクション関数、パラメータ1:集合名、パラメータ2:Schemaインスタンス
var Kitty = db.model('Kitty', mongooseSchema);

検索
model.find({}, callback);パラメータ1は無視されます.または、空のオブジェクトはすべての集合ドキュメントを返します.
mongooseSchema.statics.findbytitle = function(title, callback) {
  return this.model('mongoose').find({title: title}, callback);
}
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
var ff = mongooseModel.find({ username: 'model_demo_username'},function(e,r){
        console.log('ff',r)
      });
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes immediately, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

model.find({},field,callback);
クエリーをフィルタします.パラメータ2:{'name':1,'age':0}クエリードキュメントの戻り結果にはnameが含まれ、ageは含まれません.(_idデフォルトは1)
// name LIKE john and only selecting the "name" and "friends" fields, executing immediately
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

model.find({},null,{limit:20});
クエリーをフィルタし、パラメータ3:カーソル操作limitは、戻り結果の数を20個に制限し、20個未満であればすべてを返す.
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executing immediately
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

model.findOne({}, callback);
検索によって検出された最初のドキュメント
// find one iphone adventures - iphone adventures??
Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});

// same as above
Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});

// select only the adventures name
Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});

// same as above
Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});

// specify options, in this case lean
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);

// same as above
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);

// chaining findOne queries (same as above)
Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);

model.findById(‘obj._id’, callback);検索で見つかった最初のドキュメントは、上と同じです.ただし、__のみ受け入れます.idの値クエリー
// find adventure by id and execute immediately
Adventure.findById(id, function (err, adventure) {});

// same as above
Adventure.findById(id).exec(callback);

// select only the adventures name and length
Adventure.findById(id, 'name length', function (err, adventure) {});

// same as above
Adventure.findById(id, 'name length').exec(callback);

// include all properties except for `length`
Adventure.findById(id, '-length').exec(function (err, adventure) {});

// passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});

// same as above
Adventure.findById(id, 'name').lean().exec(function (err, doc) {});

作成
Model.create(ドキュメントデータ、callback))コレクションにドキュメントを作成する
//        model  
var doc = {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');
    }
    //        
    db.close();
});

更新
Model.update(conditions,update,function(error)パラメータ1:クエリー条件、パラメータ2:オブジェクトの更新、MondoDBの更新モディファイヤの使用
//    
//mongooseModel.update(conditions, update, options, callback);
var conditions = {username : 'model_demo_username'};
var update     = {$set : {age : 27, title : 'model_demo_title_update'}};
var options    = {upsert : true};
mongooseModel.update(conditions, update, options, function(error){
   if(error) {
       console.log(error);
   } else {
       console.log('update ok!');
   }
   //       
   db.close();
});

削除
Model.remove(conditions,callback);パラメータ1:クエリー条件
//     
var conditions = {username: 'emtity_demo_username'};
mongooseModel.remove(conditions, function(error){
    if(error) {
        console.log(error);
    } else {
        console.log('delete ok!');
    }

    //       
    db.close();
});

Model.where()
User.find({age: {$gte: 21, $lte: 65}}, callback);
  :
User.where('age').gte(21).lte(65).exec(callback);

Entity
1.コンストラクション関数、実はmodelの例です
new TestModel( { name:‘xueyou’, age:21 } );
2.作成、コレクションにドキュメントを作成します.
Entity.save(callback);
Modelによって作成されたエンティティは、saveメソッドを使用してデータを保存します.ModelもEntityもデータベースに影響を与える操作がありますが、EntityよりもModelの方が操作性があります.
var TestEntity = new TestModel({
       name : "Lenka",
       age  : 36,
       email: "[email protected]"
});
console.log(TestEntity.name); // Lenka
console.log(TestEntity.age); // 36
var mongooseModel = db.model('mongoose', mongooseSchema);
var doc = {username : 'model_demo_username', title : 'emtity_demo_title', content : 'emtity_demo_content'};
var mongooseEntity = new mongooseModel(doc);
mongooseEntity.save(function(error) {
    if(error) {
        console.log(error);
    } else {
        console.log('saved OK!');
    })

モディファイヤと更新
[更新](Update)モディファイヤ
「$inc」増減モディファイヤは、数値にのみ有効です.次の例では、age=22のドキュメントを見つけ、ドキュメントのage値を1から増やします.
 Model.update({‘age’:22}, {’$inc’:{‘age’:1} }  );
   : age=23

'$set'はキーの値を指定し、このキーが存在しない場合に作成します.任意のMondoDBでサポートされているタイプです.
 Model.update({‘age’:22}, {’$set’:{‘age’:‘haha’} }  );
   : age=‘haha’

'$unset'は上から反転し、キーを削除します.
 Model.update({‘age’:22}, {’$unset’:{‘age’:‘haha’} }  );
   : age    

配列モディファイヤ:
'$push'はキーpushに配列メンバーを与え、キーが存在しないと作成されます.
 Model.update({‘age’:22}, {’$push’:{‘array’:10} }  );
   :      array  ,     ,       10

'$addToSet'は配列に要素を追加し、存在する場合は追加しません.
 Model.update({‘age’:22}, {’$addToSet’:{‘array’:10} }  );
   : array  10      

'$each'は配列を巡り、$pushモディファイヤと組み合わせて複数の値を挿入できます.
Model.update({'age':22},{'$push':{'array':{'$each':[1,2,3,4,5]}});実行後:array:[10,1,2,3,4,5]
'$pop'配列の末尾に要素を削除
 Model.update({‘age’:22}, {’$pop’:{‘array’:1} }  );
   : array : [10,1,2,3,4]  tips:  1  -1          

'$pull'指定した要素を配列に削除
 Model.update({‘age’:22}, {’$pull’:{‘array’:10} }  );
   : array : [1,2,3,4]     array  10     

条件クエリー
「$lt」が「$lte」未満が「$gt」以上「$gte」以上が「$ne」以下である
 Model.find({“age”:{ “$get”:18 , “$lte”:30 } } );
   age     18     30   

またはクエリOR
'$in'1つのキーは複数の値'$nin'に対応しています.1つのキーは指定された値'$or'に対応していません.複数の条件が一致し、ネストされた$inは'$not'を使用して上から逆になり、特定のモードと一致しないドキュメントModel.find(「age」:{'$in:[20,21,22.'hahaha']})をクエリーします.クエリーageは20または21または'hahaha'に等しいドキュメント
 Model.find({"$or" :  [ {‘age’:18} , {‘name’:‘xueyou’} ] });
   age  18   name  ’xueyou’    

タイプクエリー
nullは自身と存在しない値を一致させることができ、キーの値をnullに一致させるには、「$exists」条件でキー値がすでに「$exists」(存在するか否かを示す)存在していると判定します.
 Model.find(“age” :  { “$in” : [null] , “exists” : true  } );
   age  null   

Model.find({name: {$exists: true}},function(error,docs){
  //      name     
});

Model.find({telephone: {$exists: false}},function(error,docs){
  //       telephone     
});

正規表現
MongoDbは、Prel互換の正規表現ライブラリを使用して正規表現をマッチングします.
 find( {“name” : /joe/i } )    
  name  joe    ,       

 find( {“name” : /joe?/i } )
           

クエリー配列
Model.find({"array":10});array(配列タイプ)キーに10のドキュメントがクエリーされ、array:[1,2,3,4,5,10]が一致します.
Model.find({"array[5]:10});クエリーarray(配列タイプ)キーの下付き5に対応する値は10であり、array:[1,2,3,4,5,10]は
'$all'は配列内の複数の要素に一致します.
 Model.find({“array”:[5,10]} );
     array      5  10   

'$size'マッチング配列長
 Model.find({“array”:{"$size" : 3} } );
     array     3    

'$slice'クエリーサブセットが返されます
 Model.find({“array”:{"$skice" : 10} } );
     array    10   
 Model.find({“array”:{"$skice" : [5,10] } } );
     array    5   10   

where
クエリーの一部としてjavacript文を実行し、コールバック関数がtrueドキュメントを返すと結果の一部として返されます.
    find( {"$where" : function(){
        for( var x in this ){
         //       this     
        }
        
        if(this.x !== null && this.y !== null){
            return this.x + this.y === 10 ? true : false;
        }else{
            return true;
        }
        
        
}  }  )

簡略化されたバージョン
    find( {"$where" :  "this.x + this.y === 10" } )
    find( {"$where" : " function(){ return this.x + this.y ===10; } " } )

カーソル
  • limit(3)戻り結果の数を制限し、
  • skip(3)最初の3つのドキュメントをスキップし、残りの
  • を返します.
  • sort({"username":1,"age":-1})ソートキーはドキュメントのキー名に対応し、値はソート方向を表し、1昇順、-1降順