對於mongodb數據庫,由於在數據映射時,事先定義好的字段可能後期需要添加。這時若直接在schema類內直接定義,是不行的。這時就需要用到.add方法作爲後期添加字段。
schema.add({
avatar : 'img.png'
});
schema的prototype屬性方法。
schema.eachPath//similar to Array forEach
schema.get(key)
schema.index({ first: 1, last: -1 })//創建索引。
schema.loadClass(model)// 引入es6 的關鍵字
virtuals
Note that if the resulting record is converted to an object or JSON, virtuals are not included by default. Pass virtuals : true to either toObject() or to toJSON() to have them returned.
用於數據庫查詢出的對象是一個自定義的json或object,由於不是mongoose支持的數據類型,所以要設置virtuals.
{
strict: true,
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
}
UserSchema.virtual('isAdvanced').get(function () {
// 積分高於 700 則認爲是高級用戶
return this.score > 700 || this.is_star;
});