mongoose方法和静态方法有什么用,它们与普通函数有何不同?
可以举个例子解释一下它们的区别吗。
数据库逻辑应封装在数据模型中。Mongoose 提供 2 种方式来实现这一点,即方法和静态方法。方法会将实例方法添加到文档中,而静态方法则将静态“类”方法添加到模型本身中。
考虑下面的Animal 模型示例:
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
的动物,我只需更改此行代码:
如果我想要检索拥有 hasTail
的动物,我只需要更改这行代码:
return this.model('Animal').find({ type: this.type }, cb);
致:
return this.model('Animal').find({ hasTail: true }, cb);
我不必创建一个静态函数。
如果您想操纵个别文档,例如添加标记等,请使用单个文档上的方法。如果您想查询整个集合,请使用静态方法。