如何自动更新mongodb字段

时间:2016-10-01 11:28:10

标签: javascript node.js mongodb mongoose database

我有一个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     
});

1 个答案:

答案 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();
});

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