What is the use of mongoose methods and statics?

后端 未结 2 1569
猫巷女王i
猫巷女王i 2021-01-30 21:20

What is the use of mongoose methods and statics and how are they different from normal functions?

Can anyone explain the difference with example.

2条回答
  •  灰色年华
    2021-01-30 21:44

    Database logic should be encapsulated within the data model. Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static "class" methods to the Models itself.

    Given the example Animal Model below:

    var AnimalSchema = mongoose.Schema({
      name: String,
      type: String,
      hasTail: Boolean
    });
    
    module.exports = mongoose.model('Animal', AnimalSchema);

    We could add a method to find similar types of animal, and a static method to find all animals with tails:

    AnimalSchema.methods.findByType = function (cb) {
      return this.model('Animal').find({ type: this.type }, cb);
    };
    
    AnimalSchema.statics.findAnimalsWithATail = function (cb) {
      Animal.find({ hasTail: true }, cb);
    };

    Here's the full model with example usage for methods and statics:

    var AnimalSchema = mongoose.Schema({
      name: String,
      type: String,
      hasTail: Boolean
    });
    
    AnimalSchema.methods.findByType = function (cb) {
      return this.model('Animal').find({ type: this.type }, cb);
    };
    
    AnimalSchema.statics.findAnimalsWithATail = function (cb) {
      Animal.find({ hasTail: true }, cb);
    };
    
    module.exports = mongoose.model('Animal', AnimalSchema);
    
    // example usage:
    
    var dog = new Animal({
      name: 'Snoopy',
      type: 'dog',
      hasTail: true
    });
    
    dog.findByType(function (err, dogs) {
      console.log(dogs);
    });
    
    Animal.findAnimalsWithATail(function (animals) {
      console.log(animals);
    });

提交回复
热议问题