【问题标题】:MongoDB - How to define multiple datatypes for a field in Mongoose?MongoDB - 如何为 Mongoose 中的字段定义多种数据类型?
【发布时间】:2016-05-29 06:10:07
【问题描述】:

这是我的 JSON:

{
    "title": "This an item",
    "date":1000123123,
    "data": [
        {
            "type": "html",
            "content": "<h1>Hi there, this is a H1</h1>"
        },
        {

            "type":"img",
            "content": [
                {
                    "title": "Image 1",
                    "url": "www.google.com/1.jpg",
                    "description":"This is the first image"
                }
            ]
        },
        {
            "type": "map",
            "content": [
                {
                    "lat":323434555,
                    "lng":4444343434,
                    "description":"this is just a place"
                }
            ]

        }
    ]
}

如您所见,“data”字段存储了一个对象数组,其中“content”字段是可变的。

我应该如何在 Mongoose 中建模?

这就是我定义架构的方式:

module.exports = mongoose.model('TestObject', new Schema({
    title: String,
    date: Date,
    data: [
        {
            type: String,
            content: Object
        }
    ]
}));

这是“数据”字段的响应:

"data": [
    {
        "type":"img",
        "content": [ "[object Object]" ]
    },
    {
        "type":"map",
        "content": [ "[object Object]" ]
    }
]

在 Mongoose 中为对象定义可变数据类型的正确方法是什么?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    也许Mixed 类型可以满足您的要求

    一个“随随便便”的 SchemaType,它的灵活性是以更难维护为代价的。 Mixed 可以通过Schema.Types.Mixed 或通过传递一个空的对象字面量来获得。

    data: [
        {
            type: String,
            content: Mixed
        }
    ]
    

    【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 2019-10-04
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2014-09-04
    • 2013-09-13
    相关资源
    最近更新 更多