简体   繁体   中英

How to create mongoose schema with array of objects

I have this 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.

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).

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

Answer to @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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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