2016-10-01 113 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