mongoose方法和统计数据的用途是什么?它们与正常函数有什么不同?
任何人都可以用例子来解释差异。
数据库逻辑应该封装在数据模型中。 Mongoose提供了两种方法,方法和静态。方法为文档添加实例方法,而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);
而且我不必创建静态函数。
如果要操作单个文档(如添加标记等),请在单个文档上使用方法。如果要查询整个集合,请使用静态方法。