【问题标题】:Relationship field within same collection?同一集合中的关系字段?
【发布时间】:2019-02-07 20:13:26
【问题描述】:

我有一个用于产品类别 (MongoDB) 的 keystonejs 模型。有些类别应该有子类别。目前我已经设置了一个关系字段“ChildCategoryOf”,我可以在管理面板中手动选择父类别。为了拥有更多功能,我想创建另一个名为“ParentCategoryOf”的字段,该字段将包含一个子类别数组。怎么可能有一个字段自动将子类别存储在数组中?我想象它是这样的:

当前型号:

let ProductCategory = new keystone.List('ProductCategory', {
    autokey: {
        from: 'name',
        path: 'key',
        unique: true
    }
});

ProductCategory.add({
    name: {
        type: String,
        required: true
    },
    ChildCategoryOf: {
        type: Types.Relationship,
        ref: 'ProductCategory',
        many: false,
        required: false,
    },
    IsParentCategory: Types.Boolean,
});

【问题讨论】:

  • 对于 1xN 关系,通常您不会让父类明确持有对子类的引用。如果您想获取所有孩子,通常会在数据库中查询具有该父 ID 的所有孩子。

标签: mongodb keystonejs


【解决方案1】:

对于 mongo 中的类别,您可以使用类似模型的继承,您可以在其中存储每个模型及其子模型的 parentId 和祖先 Id,然后向 mongoose 模型添加一个方法,以便在每次调用时添加一个子模型一个实例,这就像下面的代码:

      const ProductCategory = new Schema({
              name: String,
              parent: { type: Schema.Types.ObjectId, ref: 'ProductCategory'},
              ancestors: [{type: Schema.Types.ObjectId, ref: 'ProductCategory'}],
              children:   [{type: Schema.Types.ObjectId, ref: 'ProductCategory'}]
      });

      ProductCategory.methods = {
            addChild: function(child){
                    let that = this;
                    child.parent = this._id;
                    child.ancestors = this.ancestors.concat([this._id]);
                    return this.model('ProductCategory').create(child).addCallback 
                      (function(child){
                        that.children.push(child._id);
                        that.save();
                      });
            }
    };

然后稍后从您想按类别查找产品的位置,您应该将您找到的类别 ID 与其子 ID 连接起来,并在查找查询中使用此数组和 $in 运算符来查找一个类别中的所有产品及其子项.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2021-01-21
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多