猫鼬方法和静态有什么用? [英] What is the use of mongoose methods and statics?

查看:44
本文介绍了猫鼬方法和静态有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于猫鼬方法和静态有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆