【问题标题】:Mongoose Schema with different objects具有不同对象的猫鼬模式
【发布时间】:2020-03-10 13:41:04
【问题描述】:

我有一个看起来像这样的基本架构:

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String
    }
]});

但是项目架构可能会有所不同,我希望我可以附加具有与基本架构相同架构的新对象。这样items中的一个对象也可以有自己的items。示例:

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String
    },
    {
        key: String,
        items: [
            ...
        ]
    }
]
});

等等...这样我就可以拥有 4 个带有 idtext 的普通项目对象,或者也可以是 items 中的嵌套对象,它们又具有 keyitems[...] 属性,可以进一步重复该过程。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    一种方法是使用 Mongoose 的 Mixed 类型。

    这样说:

    let Entry = new Schema({
    key: String,
    items: [
        {
            id: Number,
            text: String,
            data: {
                type: Schema.Types.Mixed,
                default: {}
            }
        }
    ]});
    

    现在这个示例将任何“自定义”字段放在数据属性中,不确定这是否足以满足您的需求。

    用法

    const newEntry = new Entry({
        id: 1,
        text: "foobar",
        data: {
            hello: "world",
            isCorrect: true
        }
    });
    

    或者,您可以在架构上将 strict 设置为 false。

    let Entry = new Schema({
    key: String,
    items: [
        {
            id: Number,
            text: String
        }
    ]}, { strict: false});
    

    用法

    const newEntry = new Entry({
        id: 1,
        text: "foobar",
        hello: "world",
        isCorrect: true
    });
    

    我个人的偏好是第一个选项,至少这样,查看架构,我知道每条记录中都有一个混合的数据“包”,包含在“数据”字段中。两者都是在 mongoose 文档中定义的记录方法,因此完全有效。选择你的毒药:)

    参考:

    混合模式类型文档:

    https://mongoosejs.com/docs/schematypes.html#mixed

    严格的架构选项文档:

    https://mongoosejs.com/docs/guide.html#strict

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 2021-04-10
      • 2019-10-30
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2019-10-18
      相关资源
      最近更新 更多