2016-10-01 50 views
0

我有一个Category架构,我希望当children字段更改以检查其长度,如果长度等于0,那么has_children应该是false,反之亦然。如何自动更新MongoDB字段

这是我的模型:

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

has_children可能等于true,然后等于false吗?如果没有,我会说刚刚创建一个新的用户时,将has_children设置为false,然后当你添加一个孩子或创建一个新的用户与子集has_children为真然后。 – user2263572

回答

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