【发布时间】:2017-02-04 03:38:17
【问题描述】:
猫鼬方法和静态有什么用,它们与普通函数有何不同?
谁能用例子解释一下区别。
【问题讨论】:
猫鼬方法和静态有什么用,它们与普通函数有何不同?
谁能用例子解释一下区别。
【问题讨论】:
数据库逻辑应该封装在数据模型中。 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);
});
【讨论】:
如果我想用hasTail 检索动物,我可以简单地更改这行代码:
return this.model('Animal').find({ type: this.type }, cb);
到:
return this.model('Animal').find({ hasTail: true }, cb);
我不必创建静态函数。
如果您想操作单个文档,例如添加令牌等,请在单个文档上使用方法。 如果要查询整个集合,请使用静态方法。
【讨论】: