9
A
回答
21
數據庫邏輯應封裝在數據模型中。 Mongoose提供了兩種方法來完成這個任務,方法和靜態。 方法向文檔添加實例方法,而靜態將靜態「類」方法添加到模型本身。
給出的例子動物以下型號:
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);
});
相關問題
- 1. 什麼是使用貓鼬種羣的正確方法?
- 2. 貓鼬鉤:什麼是'這'
- 3. 貓鼬靜態方法填充數組
- 4. QAbstractButton :: checkStateSet()方法的用途是什麼?
- 5. SPHttpUtility.NoEncode方法的用途是什麼?
- 6. 方法attribute-target的用途是什麼?
- 7. ob_get_length()方法的用途是什麼?
- 8. 在貓鼬中定義數組的首選方法是什麼?
- 9. ControllerBase中SignIn和SignOut方法的用途是什麼?
- 10. 爲什麼我不能訪問貓鼬模式的方法?
- 11. 什麼是最好的方式來查詢這在貓鼬?
- 12. 貓鼬和子集合方法
- 13. Typescript - 爲什麼'方法'屬性不存在於貓鼬中?
- 14. 初學者學習CakePhp的最佳途徑是什麼?
- 15. CGContextSaveGState和CGContextRestoreGState的用途是什麼?
- 16. HashMap.Entry.recordAccess和recordRemoval的用途是什麼?
- 17. minOccurs,nillable和restriction的用途是什麼?
- 18. GL_COLOR_BUFFER_BIT和GL_DEPTH_BUFFER_BIT的用途是什麼?
- 19. Content.xml和Fragment.xml的用途是什麼
- 20. 動力學究竟是什麼
- 21. Java虛擬方法調用的用途是什麼?
- 22. `$ .support.ownLast`的用途是什麼?
- 23. TPopupActionBar的用途是什麼?
- 24. _GLOBAL__I_的用途是什麼?
- 25. $ _POST的用途是什麼?
- 26. 「$ this」的用途是什麼?
- 27. CreateSilverlight.js的用途是什麼?
- 28. vertexAttribPointer的用途是什麼?
- 29. RecognizerIntent.DETAILS_META_DATA的用途是什麼?
- 30. Rake的用途是什麼?