MongoDB-如何为Mongoose中的字段定义多种数据类型? [英] MongoDB - How to define multiple datatypes for a field in Mongoose?

查看:813
本文介绍了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"
                }
            ]

        }
    ]
}

如您所见,数据"字段存储了一个对象数组,其中内容"字段是可变的.

As you can see, the "data" fiel stores an array of objects where the "content" field is variable.

我应该如何在猫鼬中建模?

How should I model that in Mongoose?

这是我定义架构的方式:

This is how I defined my schema:

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

这是对数据"字段的响应:

And this is the response for the "data" field:

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

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

What is the correct way to define a varying datatype for an object in Mongoose?

推荐答案

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

Maybe the Mixed type could meet your requirement

任何东西都可以使用SchemaType,它的灵活性来自于难以维护的折衷.可以通过Schema.Types.Mixed或通过传递空的对象常量来实现混合.

An "anything goes" SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through Schema.Types.Mixed or by passing an empty object literal.

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

这篇关于MongoDB-如何为Mongoose中的字段定义多种数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆