kentor
kentor

Reputation: 18544

Map JSON object to different schema field names

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

My Schema looks like this:

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

My question:

  1. What would be the best way to map these dumb original names to my schema field names?
  2. Should I simply create a helper function or is there a mongoose feature I could use for this "mapping process"?
  3. I often see APIs which use camelCase named fields, but mongodb prefers snake_case. Should I ignore the mongodb naming conventions so that I don't need such a "mapping"?

Upvotes: 1

Views: 2037

Answers (1)

Nuspeed1
Nuspeed1

Reputation: 126

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.

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.

Upvotes: 2

Related Questions