Home > Software engineering >  Object.keys or Object.values on Mongoose Enum?
Object.keys or Object.values on Mongoose Enum?

Time:12-20

We are developing a TS project with Mongoose and we have a question about good practice and how to handle Enum on models.

We think globally of the enum as KEY -> Value pair and our vision is that "KEY" should be the "item" we are going to use to store and handle on the database, while "VALUE" should be the "translation / real meaning" of this key.

Example case:

This is our TS enum:

enum ECurrency {
  USD = 'United States dollar',
  EUR = 'Euro'
}

This is our Mongoose Schema:

...
currency: {
  type: String,
  enum: Object.keys(ECurrency),
  required: true
}

This actually works and seems to be ok.

But, when we are going to create a new document with this schema, we used to do:

currency: ECurrency.USD

This will return the value 'United States dollar' and will throw an Error.

So, the question is:

Should we use KEYS instead of the value on Mongoose Schema?

Our thinking about KEY as the reference to use and handle in the database and VALUE as the "translation" is ok?

The code above actually works, but every time we want to create a document we have to write manually "USD" or ECurrency["United States dollar"] does feel great to us and we are not sure how to handle it.

CodePudding user response:

I think you doing correctly, just store the key (USD, EUR) in the database because,

  • it would be easy to search specific currencies in the database
  • key will occupy less memory in the database

Store the key-value pair in your server or client code as constant, so can easily access it by passing the key,

You can also use the mongoose virtuals property, you can use the get property to response value instead of the key in frontend.

CodePudding user response:

Using keys or values depends on what you are storing and your own will. So don't bother if you prefer keys, go for it ! If you use 'United States dollar' and 'Euro' as "translation" putting them in a map makes more sense. This solution will also ease out the process for creating a document.

export enum Currencies {
  USD = 'USD',
  EUR = 'EUR',
}

export const ALL_LETTER_CURRENCIES: Record<Currencies, string> = {
  Currencies.USD: 'United States dollar',
  Currencies.EUR: 'Euro',
} as const

console.log(Currencies.USD)
// => USD

console.log(ALL_LETTER_CURRENCIES[Currencies.USD])
// => United States dollar

// And then you can change your code for mongoose 
...
currency: {
  type: String,
  enum: Object.values(Currencies),
  required: true
}

Whatever solution you choose, avoid using "USD" or "EUR" 'manually' because this will backfire if you want to change the wording sometime

  • Related