[英]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.