【问题标题】:How do you define a mongoDB mongoose schema for a dynamic key dictionary?您如何为动态键字典定义 mongoDB mongoose 模式?
【发布时间】:2018-03-11 17:39:59
【问题描述】:

我有一个 MongoDB 集合 users,我想在其中存储带有动态键的字典。我希望 users 在 MongoDB 中看起来像这样:

{
    "_id": {
        "$oid": "5a9f5b3400e2f61a0c5f449b"
    },
    "profile": {
        "votes": {
            dynamicKey1Here: {
                constantKey: 'value',
                constantKey2: 'value2'
            },
            dynamicKey2Here: {
                constantKey: 'value',
                constantKey2: 'value2'
            },
            // more dynamic keys here...
    }
}

但我不知道如何定义我的架构。到目前为止,我有:

const userSchema = new Schema({
    profile: {
        votes: {DynamicKeyEntry}
    }
});

那么我将如何定义DynamicKeyEntry 的架构?

const DynamicKeyEntry = new Schema(
    // HOW DO I DEFINE DYNAMIC KEYS?
);

【问题讨论】:

    标签: mongodb dictionary dynamic database-schema mongoose-schema


    【解决方案1】:

    如果您可以使用aray,那么它是存储和获取数据的更好方法:

     votes: { type: Array }
    

    现在您可以根据需要在votes 中存储多个对象

    【讨论】:

      【解决方案2】:

      因为您提到您使用的是猫鼬,所以您也可以使用 Map 或 Mixed 类型。 Map 类型允许您设置动态键并仍然为值强制执行一些架构:

      votes: {
            type: Schema.Types.Map,
            of: new Schema(
              {
                constantKey: {
                  type: Schema.Types.String,
                  required: true,
                }
              }
            )  
      ...
      

      Mixed 类型为您提供完全控制权,但您希望在应用程序端正确验证数据,否则您可能会陷入混乱。

      votes: {
         type: Schema.Types.Mixed,
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 2014-03-09
        • 2014-08-07
        • 1970-01-01
        • 2012-01-20
        • 2019-08-10
        相关资源
        最近更新 更多