简体   繁体   English

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

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

I have this json:我有这个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"
                    }
                ]
            }
        ]
    ]
}

I need to create this json into mongo database so I can get it via my node application.我需要将此 json 创建到 mongo 数据库中,以便我可以通过我的节点应用程序获取它。

This is my current schema:这是我当前的架构:

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

My greatest problem is I don't know how to add other objects into my schema to replicate the json, in MySQL I would do it with a hasmany relationship and add the correspondent id into the questions and options, but in this case I need to do via Mongo(create the json and get it via a route).我最大的问题是我不知道如何将其他对象添加到我的模式中来复制 json,在 MySQL 中我会用 hasmany 关系来做,并将通讯员 id 添加到问题和选项中,但在这种情况下我需要通过 Mongo 执行(创建 json 并通过路由获取它)。

How can I do that programatically?我怎样才能以编程方式做到这一点? Thanks in advance.提前致谢。

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
                }
            ]
        }
    ]
]

This should be schema for this JSON这应该是此 JSON 的架构

Answer to @Prathamesh More :回答@Prathamesh More

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

Arrays implicitly have a default value of [] (empty array), so no need for a default keyword数组隐式具有 [](空数组)的默认值,因此不需要default关键字

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

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