我有一个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
});
答案 0 :(得分:0)
保持
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();
});