使模型成为自己的集合

时间:2016-07-05 02:38:03

标签: javascript mongodb collections model sails.js

标题可能不清楚,但我想要实现的是使用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”属性添加到类别中。我知道这可能不是最好的方法,有什么建议吗?

1 个答案:

答案 0 :(得分: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);
      }
    }
  };

如果您有任何疑问,请告诉我。

相关问题