This is my JSON:
{
"title": "This an item",
"date":1000123123,
"data": [
{
"type": "html",
"content": "
Hi there, this is a 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?
解决方案
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
}
]