猫鼬方法和静态有什么用?

问题描述:

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

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

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

Can anyone explain the difference with example.

数据库逻辑应该封装在数据模型中.Mongoose 提供了两种方法来做到这一点,方法和静态.方法向文档添加实例方法,而静态向模型本身添加静态类"方法.

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.

以下面的动物模型为例:

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