将 JSON 对象映射到不同的架构字段名称 [英] Map JSON object to different schema field names

查看:54
本文介绍了将 JSON 对象映射到不同的架构字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a schema which is supposed to save data which comes from a third party API. Unfortunately the given names by that API are kinda poor and I would like to use proper names for my schema / database.

API 响应示例:我缩短了很多回复.它有大约 20 个字段.

API response example: I shortned the response a lot. It has around 20 fields.

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. 我经常看到使用驼峰命名字段的 API,但 mongodb 更喜欢snake_case.我是否应该忽略 mongodb 命名约定以便我不需要这样的映射"?

推荐答案

不确定您对此方法的看法,但您也可以将值附加到架构字段,稍后可能会通过选项对象引用这些值.

Not sure what you think about this approach but you can also append values to the schema field that may later be referenced through the options object.

例如,我将 alias 添加为 street 和 zip 的属性.

For example, I added alias as a property to street and zip.

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

然后可以通过猫鼬引用.检查调试控制台中星号包围的字段的结构.

Which can then be referenced through mongoose. Check the fields surrounded by asterisks in your debug console for it's structure.

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

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

Then you can use it in a loop to find the schema property's other name.

这篇关于将 JSON 对象映射到不同的架构字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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