代码之家  ›  专栏  ›  技术社区  ›  Milad

如何在MongoDB模式中创建嵌套对象、嵌套对象和数组均值堆栈

  •  1
  • Milad  · 技术社区  · 7 年前

    我试图设计一个嵌套的MongoDB模式。

    目前,我有这个模式,它正在工作:

    var CompanySchema = new mongoose.Schema({
        name: String,
        rate: number
        date: Date
    })
    

    但我想用它来获得:

    var CompanySchema = new mongoose.Schema({
        name: String,
        currency: {
            mxn: Number,
            php: Number,
        },
        source: [String],
        deliveryMethod: [String],
        date: Date
    })
    

    对于source,我想获得一个输入数组,例如[“银行”、“借记卡”、“代理”] deliverymethod也差不多。

    但要么我的输入错误,要么我的模式错误,因为源代码的值保存为一个长字符串,而不是一个单独的值。

    此外,我认为我设计货币以获得更高汇率的方式是正确的,但我不知道我的输入json应该是什么。

    我在《邮递员》中试过:

    {
        "name": "google",
        "currency": {
            "mxn": 20,
            "php": 30
        }
    } 
    

    这是我得到的结果:

    {
    "status": 201,
    "data": {
        "__v": 0,
        "name": "google",
        "date": "2017-12-06T22:38:45.896Z",
        "_id": "5a2871752e3b7343dc388549",
        "deliveryMethod": [
            null
        ],
        "source": [
            null
        ]
    },
    "message": "Succesfully Created  Company"
    }
    

    1-如果我的货币嵌套模式正确,我的post json文件应该是什么?

    2-如何将source和deliveryMethod作为字符串数组获取?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mika Sundland    7 年前

    请求正文中的JSON应该如下所示:

    {
        "name": "google",
        "currency": {
            "mxn": 20,
            "php": 30
        },
        "source": ["source1", "source 2", "source 3"],
        "deliveryMethod": ["delMetd 1", "delMetd 2", "delMetd 3"],
        "date": "2015-11-27T23:00:00Z"
    }
    

    我复制/粘贴了你的代码,并尝试与邮递员。我得到的回复是:

    {
        "__v": 0,
        "name": "google",
        "date": "2015-11-27T23:00:00.000Z",
        "_id": "5a2915295c5f714f7cb25d90",
        "deliveryMethod": [
            "delMetd 1",
            "delMetd 2",
            "delMetd 3"
        ],
        "source": [
            "source1",
            "source 2",
            "source 3"
        ],
        "currency": {
            "mxn": 20,
            "php": 30
        }
    }
    

    如果我用mongo shell连接到数据库并运行 db.companies.find().pretty() 我得到了这个结果:

    {
            "_id" : ObjectId("5a2915295c5f714f7cb25d90"),
            "name" : "google",
            "date" : ISODate("2015-11-27T23:00:00Z"),
            "deliveryMethod" : [
                    "delMetd 1",
                    "delMetd 2",
                    "delMetd 3"
            ],
            "source" : [
                    "source1",
                    "source 2",
                    "source 3"
            ],
            "currency" : {
                    "mxn" : 20,
                    "php" : 30
            },
            "__v" : 0
    }
    

    您的模式很好。你可以试着删除收藏( db.companies.drop() )如果你不能让它工作。如果你没有任何重要数据,就从一个新的开始。