【问题标题】:How to create mongoose schema with array of objects如何使用对象数组创建猫鼬模式
【发布时间】:2018-11-30 07:39:40
【问题描述】:

我有这个 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 并通过路由获取)。

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

【问题讨论】:

    标签: node.js mongodb mongoose-schema


    【解决方案1】:
    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: [] }
    【解决方案2】:

    回复@Prathamesh More

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2019-02-20
      • 2016-03-09
      • 2019-10-30
      • 1970-01-01
      • 2019-03-21
      • 2012-04-22
      • 2015-03-25
      相关资源
      最近更新 更多