MongoDB - 如何为Mongoose中的字段定义多个数据类型?

时间:2016-02-17 13:43:17

标签: mongodb mongoose

这是我的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"
                }
            ]

        }
    ]
}

如您所见,“数据”字段存储“内容”字段可变的对象数组。

我应该如何在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中为对象定义变化数据类型的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

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

  

“任何事情都有”SchemaType,它的灵活性来自于它难以维护的权衡。混合可通过Schema.Types.Mixed或通过传递空对象文字来获得。

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