【问题标题】:What is the use of mongoose methods and statics?猫鼬方法和静态有什么用?
【发布时间】:2017-02-04 03:38:17
【问题描述】:

猫鼬方法和静态有什么用,它们与普通函数有何不同?

谁能用例子解释一下区别。

【问题讨论】:

    标签: methods mongoose schema


    【解决方案1】:

    数据库逻辑应该封装在数据模型中。 Mongoose 提供了两种方法,方法和静态。 Methods 向文档添加实例方法,而 Statics 向模型本身添加静态“类”方法。

    给出下面的示例动物模型:

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

    我们可以添加一个方法来查找相似类型的动物,以及一个静态方法来查找所有有尾巴的动物:

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

    这是完整的模型以及方法和静态的示例用法:

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

    【讨论】:

      【解决方案2】:

      如果我想用hasTail 检索动物,我可以简单地更改这行代码:

      return this.model('Animal').find({ type: this.type }, cb);
      

      到:

      return this.model('Animal').find({ hasTail: true }, cb);
      

      我不必创建静态函数。

      如果您想操作单个文档,例如添加令牌等,请在单个文档上使用方法。 如果要查询整个集合,请使用静态方法。

      【讨论】:

      • 这是一个很好的答案。我不知道复制和粘贴文档有什么好处:)。你已经直截了当。
      猜你喜欢
      • 2014-07-15
      • 2020-09-11
      • 2011-04-23
      • 2016-08-28
      • 1970-01-01
      • 2018-10-28
      • 2013-07-21
      • 2012-11-02
      • 2021-08-07
      相关资源
      最近更新 更多