繁体   English   中英

如何使用对象数组创建猫鼬模式

[英]How to create mongoose schema with array of objects

我有这个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 数据库中,以便我可以通过我的节点应用程序获取它。

这是我当前的架构:

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 并通过路由获取它)。

我怎样才能以编程方式做到这一点? 提前致谢。

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 的架构

回答@Prathamesh More

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM