将JSON对象映射到不同的架构字段名称

时间:2017-07-29 02:58:58

标签: json node.js mongodb mongoose

我创建了一个架构,用于保存来自第三方API的数据。不幸的是,该API给出的名称有点差,我想为我的架构/数据库使用专有名称。

API响应示例: 我把响应缩短了很多。它有大约20个领域。

let apiResponse = {
    id: {high:1, low:388},
    username:"xyz",
    addr: [{
        fdn: "Street 123",
        dq: "5534"
    },{
        fdn: "Street 456",
        dq: "1102"
    }]
}

我的架构如下所示:

let userSchema = mongoose.Schema({
    account_id: {
        high: {
            type: Number,
            required: true
        },
        low: {
            type: Number,
            required: true
        }
    },
    username: {
        type: String,
        required: true,
        index: true
    },
    addresses: [{
        street: {
            type: String,
            required: true
        },
        zip: {
            type: Number,
            required: true
        }
    }],
})

我的问题:

  1. 将这些愚蠢的原始名称映射到我的架构字段名称的最佳方法是什么?
  2. 我应该简单地创建一个辅助函数,还是有一个猫鼬功能可以用于这个“映射过程”?
  3. 我经常看到使用camelCase命名字段的API,但mongodb更喜欢snake_case。我是否应该忽略mongodb命名约定,以便我不需要这样的“映射”?

1 个答案:

答案 0 :(得分:1)

不确定您对此方法的看法,但您也可以将值附加到架构字段,稍后可以通过options对象引用它。

例如,我将别名添加为街道和zip的属性。

let userSchema = mongoose.Schema({
    ...
    addresses: [{
        street: {
            type: String,
            required: true,
            **alias**: "fdn"
        },
        zip: {
            type: Number,
            required: true,
            **alias**: "dq"
        }
    }],
})

然后可以通过mongoose引用。检查调试控制台中星号包围的字段是否有结构。

mongoose.models.**UserSchema**.schema.paths.**addresses.street**.options.alias

然后,您可以在循环中使用它来查找架构属性的其他名称。

相关问题