小智 40
数据库逻辑应该封装在数据模型中.Mongoose提供了两种方法,方法和静态.方法为文档添加实例方法,而Statics向模型本身添加静态"类"方法.
给出下面的动物模型示例:
var AnimalSchema = mongoose.Schema({
name: String,
type: String,
hasTail: Boolean
});
module.exports = mongoose.model('Animal', AnimalSchema);Run Code Online (Sandbox Code Playgroud)
我们可以添加一种方法来查找相似类型的动物,并使用静态方法查找所有带尾巴的动物:
AnimalSchema.methods.findByType = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
AnimalSchema.statics.findAnimalsWithATail = function (cb) {
Animal.find({ hasTail: true }, cb);
};Run Code Online (Sandbox Code Playgroud)
这是完整的模型,包含方法和静态的示例用法:
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);
});Run Code Online (Sandbox Code Playgroud)
小智 9
如果我想检索动物,hasTail我可以简单地更改这行代码:
return this.model('Animal').find({ type: this.type }, cb);
Run Code Online (Sandbox Code Playgroud)
到:
return this.model('Animal').find({ hasTail: true }, cb);
Run Code Online (Sandbox Code Playgroud)
而且我不必创建静态函数。
如果要操作单个文档(如添加令牌等),请在单个文档上使用方法。如果要查询整个集合,请使用静态方法。
| 归档时间: |
|
| 查看次数: |
10331 次 |
| 最近记录: |