如何使用对象数组创建猫鼬模式 [英] How to create mongoose schema with array of objects

查看:39
本文介绍了如何使用对象数组创建猫鼬模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create this json into mongo database so I can get it via my node application.

这是我当前的模式:

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关系将其添加到问题和选项中,但是在这种情况下我需要通过Mongo(创建json并通过路由获取).

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

这应该是此JSON的架构

This should be schema for this JSON

这篇关于如何使用对象数组创建猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆