zoukankan      html  css  js  c++  java
  • Mongoose 'static' methods vs. 'instance' methods

    statics are the methods defined on the Model

    methods are defined on the document (instance).

    We may also define our own custom document instance methods too.

    // define a schema
    var animalSchema = new Schema({ name: String, type: String });
    
    // assign a function to the "methods" object of our animalSchema
    animalSchema.methods.findSimilarTypes = function (cb) {
      return this.model('Animal').find({ type: this.type }, cb);
    }

    Now all of our animal document instances have a findSimilarTypes method available to it.

    And then:

    Adding static methods to a Model is simple as well. Continuing with our animalSchema:

    // assign a function to the "statics" object of our animalSchema
    animalSchema.statics.findByName = function (name, cb) {
      return this.find({ name: new RegExp(name, 'i') }, cb);
    }
    
    var Animal = mongoose.model('Animal', animalSchema);
    Animal.findByName('fido', function (err, animals) {
      console.log(animals);
    });

    You might do,  

    Animal .  Modal
    Animal.findByName('fido', function(err, fido){
        // fido => { name: 'fido', type: 'dog' }
    });

    And then you might use the document instance fido to do

    fido .  document

    fido.findSimilarTypes(function(err, dogs){
        // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
    });
  • 相关阅读:
    问题 A: C#抽象类Vehicles
    最短路练习
    BFS
    poj 1083 Moving Tables
    组合数
    hdu 1443 Joseph【约瑟夫环】
    poj 2449 Remmarguts' Date【第K短路】
    hdu 1695 GCD 【莫比乌斯函数】
    hdu 2178 猜数字
    bzoj 2440 完全平方数 【莫比乌斯函数】
  • 原文地址:https://www.cnblogs.com/Joans/p/10599880.html
Copyright © 2011-2022 走看看