繁体   English   中英

如何自动更新mongodb字段

[英]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();
});

参考: http : //mongoosejs.com/docs/middleware.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM