【问题标题】:Mongoose self nesting猫鼬自我筑巢
【发布时间】:2017-12-09 15:23:45
【问题描述】:

我想存储以下内容:

var TestSchema = new Schema({
    name: {
        type: String
    },
    regions: [RegionSchema]
}

var RegionSchema = new Schema({
    name: {
        type: String
    },
    minX: {
        type: Number
    },
    minY: {
        type: Number
    },
    minZ: {
        type: Number
    },
    maxX: {
        type: Number
    },
    maxY: {
        type: Number
    },
    maxZ: {
        type: Number
    },
    children: [this]
});

如您所见,我正在尝试创建一个能够包含区域对象的区域对象,但是这无一例外地无法保存,大概是架构中的 [this] 陷入了某种无限循环或其他东西。

如何使它适用于嵌套区域?

我希望发送到此架构的 json 有效负载:

name: "test123",
regions: [
        {
            name: "TestRegion",
            minX: 0,
            minY: 0,
            minZ: 0,
            maxX: 100,
            maxY: 255,
            maxZ: 100,
            children: [
                {
                    name: "TestRegionChild",
                    minX: 3,
                    minY: 3,
                    minZ: 3,
                    maxX: 97,
                    maxY: 252,
                    maxZ: 97,
                    children: []
                }
            ]
        }
    ]

感谢您的帮助,谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    如果您的其他区域先保存,您可以将子区域保存为 objectIds 列表,如下所示:

    children: [{
         type: Schema.ObjectId,
         ref: 'Region'
    }]
    

    另一种选择是重新设计您的架构并在您的区域上添加一个“父级”并删除“子级”字段。然后,当您需要获取所有子对象时,您可以轻松查询并且没有大的嵌套对象。

    var RegionSchema = new Schema({
         --- other fields omitted ---
    
         parent: {
            type: Schema.ObjectId,
            ref: 'Region'
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 2015-04-06
      • 2018-01-21
      相关资源
      最近更新 更多