Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - How to define multiple datatypes for a field in Mongoose?

This is my 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]" ]
    }
]

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

like image 735
Boel Avatar asked Jan 25 '26 18:01

Boel


1 Answers

Maybe the Mixed type could meet your requirement

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
    }
]
like image 121
zangw Avatar answered Jan 28 '26 21:01

zangw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!