如何创建包含对象数组的mongoose模式

8

我有这个JSON:

{
    "data": [
        "id": "1",
        "name": "Sample test",
        "description": "this is a sample test",
        "category": "tests",
        "points": 100,
        "startDate":"2018-02-15 00:00:00",
        "endDate":"2018-02-22 00:00:00",
        "isActive":true,
        "alreadyAnswered":false,
        "questions":[
            {
                "id": 1,
                "text": "What is your name",
                "type": "text",
            },
            {
                "id": 2,
                "text": "What is your favorite color",
                "type": "select",
                "options": [
                    {
                        "id": 1,
                        "text": "Red",
                        "value": "red"
                    },
                    {
                        "id": 2,
                        "text": "Blue",
                        "value": "blue"
                    }
                ]
            }
        ]
    ]
}

我需要将这个json创建到mongo数据库中,以便我可以通过我的node应用程序获取它。

这是我的当前模式:

let TestSchema = new Schema({
    id: Number,
    name: String,
    description: String,
    category: String,
    points: Number,
    startDate: Date,
    endDate: Date,
    isActive: Boolean,
    alreadyAnswered: Boolean
});

我的最大问题是不知道如何将其他对象添加到我的模式中来复制json,在MySQL中,我将使用hasmany关系并将对应的id添加到问题和选项中,但在这种情况下,我需要通过Mongo创建json并通过路由获取它。如何以编程方式完成此操作?谢谢。
2个回答

18
data: [
    id: String, //or number, whatever you need
    name: String,
    description: String,
    category: String,
    points: Number,
    startDate​:​ Date,
    endDate​: ​Date,
    isActive​: ​Boolean​,
    alreadyAnswered​:​ Boolean​,
    questions:[{
            id: String, //or again, number
            text: String,
            type: String,
            options: [
                {
                    id: String, //or number
                    text: String,
                    value: String
                }
            ]
        }
    ]
]

这应该是这个 JSON 的架构


我该如何为这种类型进行定义:device_meta: { type: Array, default: [] } - Prathamesh More

0

回答 @Prathamesh More:

device_meta: [{
   // For example
   device_name: String,
   ID: Number
}]

数组隐式地具有默认值[](空数组),因此不需要使用default关键字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接