[英]how to auto update mongodb field
我有一個Category
架構,我想當children
字段更改時檢查其長度,如果長度等於0,則has_children
應該為false
,而相反。
這是我的模型:
const category_item = new mongoose.Schema({
//...other fields...,
children: { type: Array, required: true, default: [] }
has_children: // if children length equal to 0 get false and opposite
});
保持
const category_item = new mongoose.Schema({
...anotherFields...,
children : {type : Array , required : true , default : []}
has_children : {type: Boolean}
});
並添加一個預保存鈎
category_item.pre('save', function(next) {
if (this.children && this.children.length > 0) {
this.has_children = true;
} else {
this.has_children = false;
}
next();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.