Node.jsのMongoDBドライバMongoose基本使用教程

6502 ワード

monogorsを使うと、より多くの業務ロジックを書く必要がなく、mongodbデータベースを使うことができます.
インストール

npm install mongoose
初期化は、monodeと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() {
  //         
 }
クイックエントリは、monogoogleにおいて、すべてのデータが一つのパターンであり、各モードがmongodbのセットにマッピングされ、このセットファイル構造を定義する.

 //           ,                 
 var animalSchema = new Schema({
  name: String,
  age: Number,
 });
モデルはSchemaから定義された多様な構造関数であり、モデルの例は多くの動作を使用することができます.すべてのドキュメントの作成と検索はモデルによって処理されます.

 var animalMode = db.model('Animal', animalSchema);
モデルの実例は実質的にファイルです.このようなファイルを簡単に作成し、修正できます.

 var cat = new animalMode({
  name: 'catName',
  age: '7', //         ,mongoose       
  });

 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);
 //});

 //    
 animalMode.find(function(err, people){
  if(err) console.log(err);
  console.log(people);
 });
 //        
 animalMode.findOne({title: 'catName'}, function(err, cat){
  if(err) console.log(err);
  console.log(cat);
 });

Schemaデータタイプ
これはSchemaの中のすべてのデータのタイプで、monogoogleが決めたデータのタイプを含みます.
  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Aray
  • データの種類ごとの使用
    
     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はmongoogleがカスタマイズしたハイブリッドタイプです.Mixedは具体的な内容を定義していませんので、以下の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に静的な方法を追加することもできます.
    
     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);
     });
    
    
    索引
    私たちはmonogodbデータのためにインデックスを作成することができます.mongodbは2つのインデックスをサポートしています.データの検索と位置付けを向上させるためには、複合インデックスを作成する必要があります.
    
     var animalSchema = new Schema({
      name: String,
      age: Number,
      tags: { age: [String], index: true } // field level
     });
    
     animalSchema.index({ name: 1, age: -1 }); // schema level
    
    
    しかし、このインデックスの確立は、顕著な性能に影響を与える可能性があります.生産を停止し、設定モードの自動インデックスを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
    
    //find
    animalMode.find(function(err, cat){
     if (err) console.log(err);
     console.log(cat);
    })
    
    //findOne
    animalMode.findOne({name: 'catName'}, function(err, cat){
     if (err) console.log(err);
     console.log(cat);
    })
    
    //findByID
    //  findOne   ,        _id     ,      。_id //        ObjectId   。
    animalMode.findById(id, function(err, adventure){
     if (err) consoel.log(err);
     console.log(adventure);
    });
    
    //where
    //           ,     
    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公式文書で提供される更新関数Model.udate
    Model.update(conditions,doc,[options],[calback])
  • conditions更新条件
  • doc更新内容
  • option更新オプション
  • safe安全モード、標準オプション、値はtrue
  • です.
  • up sert条件が一致しない場合、新しい文書を作成するかどうか、標準値はfalse
  • です.
  • multiは複数のファイルを更新するかどうか、デフォルトはfalse
  • です.
  • strict(bollan)厳格なモード、1本のデータだけを更新します.
  • overwrite(bollan)データをカバーし、デフォルトはfalse
  • です.
  • calback
  • errデータ更新エラー時戻り値
  • number Affected
  • rawResonseが影響を受ける行数
  • 
    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);
    })
    
    その他/ドキュメントの数を返します.
    
    animalMode.count({age: 2}, function(err, cat){
     if (err) console.log(err);
     console.log(cat);
    })