这是我的 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"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
如您所见,“数据”字段存储了一个对象数组,其中“内容”字段是可变的。
我应该如何在猫鼬中建模?
这就是我定义架构的方式:
module.exports = mongoose.model('TestObject', new Schema({
title: String,
date: Date,
data: [
{
type: String,
content: Object
}
]
}));
Run Code Online (Sandbox Code Playgroud)
这是“数据”字段的响应:
"data": [
{
"type":"img",
"content": [ "[object Object]" ]
},
{
"type":"map",
"content": [ "[object Object]" ]
}
]
Run Code Online (Sandbox Code Playgroud)
在 Mongoose 中为对象定义不同数据类型的正确方法是什么?
也许Mixed类型可以满足您的要求
“任何事情都可以”的 SchemaType,它的灵活性来自于它更难维护的权衡。Mixed 可通过
Schema.Types.Mixed或通过传递空对象字面量来使用。
data: [
{
type: String,
content: Mixed
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5360 次 |
| 最近记录: |