使模型成为自身的集合

Make a model a collection of itself

本文关键字:集合 模型      更新时间:2023-09-26

标题可能不清楚,但我想要实现的是具有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);
    }
  }
};

它似乎不工作。我在控制器sc中调用addSubCategory这个值是正确的,但它从未将subCategory属性添加到类别中。我知道这可能不是最好的方法,有什么建议吗?

不需要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);
      }
    }
  };
如果您有任何疑问请告诉我。