2016-07-05 84 views
0

標題可能不清晰,但我想要實現的是使用parentCategories的類別。例如:將模型作爲自己的集合

/-Clothes 
/---Men 
/---Women 
/---Kids 
/-----Newborns 

所以我想我可以讓每個類別有一個可選的父類,每當我添加類別與父母一個,發現這個父類和新的子類別添加到它。我清楚了嗎?

這是我迄今所做的:

Category.js(型號)

module.exports = { 
    connection: 'MongoDB', 

    attributes: { 
    name: { 
     type: 'string', 
     required: true, 
     unique: true 
    }, 
    description: { 
     type: 'string' 
    }, 
    products: { 
     collection: 'product', 
     via: 'category' 
    }, 
    parentCategory: { 
     model: 'category' 
    }, 
    subCategories: { 
     collection: 'category', 
     via: 'parentCategory' 
    }, 

    addSubCategory: function(sc) { 
     this.subCategories.push(sc); 
    } 
    } 
}; 

它似乎沒有奏效。我從我的控制器調用addSubCategory,sc,並且這個值是正確的,但是它永遠不會將「subCategory」屬性添加到類別中。我知道這可能不是最好的方法,有什麼建議嗎?

回答

0

您不需要subCategories屬性。以下設計將是我的建議。

module.exports = { 
    connection: 'MongoDB', 

    attributes: { 
     name: { 
     type: 'string', 
     required: true, 
     unique: true 
     }, 
     type: { 
     type: 'string', 
     enum: ['parent', 'subcategory'], 
     }, 
     description: { 
     type: 'string' 
     }, 
     products: { 
     collection: 'product', 
     via: 'category' 
     }, 
     parentCategory: { 
     model: 'category' // this exists only if type is 'subcategory' else null 
     }, 

     addSubCategory: function(sc) { 
     this.subCategories.push(sc); 
     } 
    } 
    }; 

讓我知道你是否有任何疑問。

+0

這不會搜索父類別,並添加新的suncategory。我想要填充分層次的類別 –

+0

您也可以爲'Subcategory'創建另一個模型,但設計明智我認爲這個模型應該完美。您可以使用「異步」塊填充數據。 – khushalbokadey