使用不确定数量的嵌套对象构建Mongoose Schema

时间:2016-07-06 12:31:29

标签: mongoose mongoose-schema

1。仪表板菜单数据示例:

const dashboards = [
  {"dashboard": "sample",
    "items": [
      { "title": "Title 1" },
      { "title": "Title 2",
        "items": [
          { "title": "Title 2-1",
            "items": [
              { "title": "Title 2-1-1" },
              { "title": "Title 2-1-2" }
            ]
          },
          { "title": "Title 2-2" }
        ]
      },
      { "title": "Title 3",
        "items": [
          { "title": "Title 3-1" },
          { "title": "Title 3-2",
            "items": [
              { "title": "Title 3-2-1" },
              { "title": "Title 3-2-2" }
            ]
          }
        ]      },
      { "title": "Title 4",
        "items": [
          { "title": "Title 4-1" },
          { "title": "Title 4-2",
            "items": [
              { "title": "Title 4-2-1" },
              { "title": "Title 4-2-2",
                "items": [
                  { "title": "Title 4-2-2-1" },
                  { "title": "Title 4-2-2-2" }
                ]              
              }
            ]
          }
        ]      
      }
  ]}
];

2。我的架构尝试:

    const DashboardMenuSchema = new Schema({
      title: {type: String},
      items: [{
        title: String
      }]
    }, { _id: true });

    DashboardMenuSchema.add({ items: [DashboardMenuSchema.items] });

我的架构没有按预期工作。

满足和不确定菜单项数量的正确方法是什么?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

原来这很直接......

const ItemSchema = new mongoose.Schema({
  title: {type: String},
});


export const DashboardMenuSchema = new mongoose.Schema({
  title: {type: String},
  items: [ItemSchema]
}, { _id: true });

DashboardMenuSchema.add({ items: [DashboardMenuSchema.items] });