简体   繁体   中英

how to auto update mongodb field

I have a Category schema and I want when children field changes to check its length and if the length is equal to 0 then has_children should be false and the opposite should apply.

This is my model :

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     
});

keep

const category_item = new mongoose.Schema({

    ...anotherFields...,
    children : {type : Array , required : true , default : []}
    has_children : {type: Boolean}
});

and add a pre save hook

category_item.pre('save', function(next) {
    if (this.children && this.children.length > 0) {
        this.has_children = true;
    } else {
        this.has_children = false;
    }
    next();
});

Reference: http://mongoosejs.com/docs/middleware.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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