How can I use Object.keys or Object.values for Mongoose Enum fields?

We are currently working on a TypeScript project using Mongoose and have a question regarding best practices for handling Enums in models.

Our perspective is to view the enum as a KEY -> Value pair, where the "KEY" represents the item stored in the database and the "VALUE" signifies its real meaning or translation.

For example:

Here is our TypeScript enum:

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

And here is our Mongoose Schema:

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

So far, this setup appears to be functioning correctly.

However, when creating a new document with this schema, we typically use:

currency: ECurrency.USD

This returns 'United States dollar' and may result in an Error.

Therefore, our question is:

Should we utilize KEYS rather than values in the Mongoose Schema?

Is our concept of using the KEY as a reference for database operations and VALUE as a form of translation valid?

The current code works, but the manual input of "USD" or ECurrency["United States dollar"] each time we create a document feels cumbersome and we are uncertain about how to streamline this process.

Answer №1

It's important to properly store the key (USD, EUR) in your database for several reasons:

  • Searching for specific currencies in the database will be easier
  • Keys take up less memory in the database

To make accessing the key-value pair simple, consider storing them as constants in your server or client code. This way, you can easily retrieve values by passing the corresponding key.

If you're using Mongoose, check out the mongoose virtuals property. You can use the get property to display the value instead of the key in the frontend.

Answer №2

Deciding between keys or values for storage depends on the nature of your data and personal preference. So, if you have a preference for keys, go ahead and use them! For instance, if you are dealing with currencies like 'United States dollar' and 'Euro' as "translations", it would be more logical to store them in a map. This approach not only streamlines the process but also simplifies document creation.

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

// You can then update your mongoose code 
...
currency: {
  type: String,
  enum: Object.values(Currencies),
  required: true
}

Regardless of the approach you take, refrain from hardcoding "USD" or "EUR" manually, as this could lead to complications if you need to modify the terminology later on.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Managing the sequence of module loading in NodeJS

Consider this scenario: There are 3 files (modules) involved: app.js (async () => { await connectoDB(); let newRec = new userModel({ ...someprops }); await newRec.save(); })(); The app.ts serves as the entry point of the project. database ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

What is the best way to enhance the default constructor for an object with MongoMapper?

Recently, I started using MongoMapper to handle nested models within a Sinatra application. Specifically, I needed to validate a field when an EmbeddedDocument is initialized and add a leading slash if one is not present. My initial thought was to create ...

What is the best way to locate matching values in Mongoose fields?

Need assistance in finding matches with the same match_id using mongoose. I am struggling to come up with a solution. Any help would be greatly appreciated. Thank you. The match_id is of type String and I need to identify duplicate matches that are being ...

Insert a symbol at the beginning of the Autocomplete component in Material-UI

I am looking to enhance the Autocomplete component by adding an icon at the beginning using startAdornment. I discovered that Autocomplete functions as a regular text input. My attempt so far involved inserting: InputProps={{startAdornment: <InputAdorn ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

Tips for creating a mock object for a class that was instanced with the `new`

class MyClass { async myMethod(req, res):Promise<any>{ const result = await new Helper().doSomething() } } When creating a unit test for myMethod, how can we mock the Helper class method? ...

When posting on social platforms, the URL fails to display any metadata

We recently completed a project (Web Application) using React .net core with client-side rendering in React. One challenge we encountered was that when the app loads in the browser, it only displays the static HTML initially without the dynamic meta tags. ...

What is causing the issue with fetching data from MongoDB in my basic web application?

Recently, I have been trying to integrate MongoDB into my Express Node.js web application. Being fairly new to Node.js, I decided to follow a tutorial video [link to video] for guidance. Unfortunately, I encountered some difficulties while setting up the M ...

Retrieve distinct values in Mongodb using the find() query to eliminate any duplicate entries

In my possession is a set of various documents: { "networkID": "myNetwork1", "pointID": "point001", "param": "param1" } { "networkID": "myNetwork2", "pointID": "point002", "param": "param2" } { "networkID": "myNetwork1", "p ...

Intellisense not working with express

After using the command npm install --save @types/express to install, I imported in my ts file as follows: import * as express from "express"; var app = express(); Despite this setup, I am not able to get intelisense on the app variable. Additionally ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Tips for passing certain optional parameters while excluding others without resorting to undefined or empty values like ""

Is there a way to invoke the function while omitting certain optional parameters without resorting to undefined and empty strings? import { MouseEvent } from "react"; import { DialogType } from "editor-constants"; export interface Dial ...

Tips for refreshing the current Angular 2 Component

I'm looking for a way to refresh the same component in Angular 2. Can anyone provide guidance? Below is the code snippet I have: import { Component, OnInit, ElementRef, Renderer } from '@angular/core'; import { Router, ActivatedRoute, Para ...

Having trouble retrieving the value of an HTML input field using form.value in Angular 5?

I am currently working with Angular 5 Within my HTML, I am dynamically populating the value of an input field using: <input type="number" class="form-control" id="unitCost" name="unitCost" [(ngModel)]="unitCost" placeholder="Average Unit Price"> ...

Pymongo 3.6 failing to properly validate keys

I am experiencing an issue with inserting keys in mongo that require dots. Previously, I used 'check_keys = False' while inserting with pymongo3.4 and it worked fine. However, after updating to pymongo3.6, I am encountering the InvalidDocument Er ...

Having trouble importing a variable from a precompiled library in TypeScript JavaScript

Here is the content of my package.json file: { "name": "deep-playground-prototype", "version": "2016.3.10", "description": "", "private": true, "scripts": { "clean": "rimraf dist", "start": "npm run serve-watch", "prep": "browserify ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...