Attempting to implement dynamic selectors in my functions to avoid redundancy

Here is some code I find myself writing frequently for parsing JSON or creating functions.

// Reusable adder functions
async function addImagesToEntity(entityId, fileName, entity) {
  const entity = await db.${entity}.findById(entityId);
  await entity.${entity}Images.push({'fileName':fileName});
  entity.updated = Date.now();
  await entity.save();
  //console.log(entity);
}

// I often repeat this pattern for many of my services, and I'm looking to extend it to cover most frontend and backend functionalities. If I can figure out how to do this, I can have a single "CRUD" service for the majority of my use cases.

I encounter this issue frequently when dealing with complex JSON objects and creating dynamic selectors...

I use ${} because that's how I construct strings dynamically, but I am unable to apply it to functions or naming conventions. I want to be able to use a string variable as a function name or method, which is not currently possible. Thank you to anyone who can assist me with this challenge.

Thank you in advance!

Answer №1

One approach could be to implement a solution using a hashMap that stores individual values for easy access.

const dataMap = {
  'pet': {
    database: "Pet",
    key: 'petImages'
  },
  'account': {
    database: "Account",
    key: 'accountImages'
  },
  'property':{
    database: "Property",
    key: 'propertyImages'
  }
}

async function addImagesToEntity(entityId, fileName, entityType) { // The entityType will correspond to the keys in the object above.
  const {database, key} = dataMap[entityType];
  const entity = await db[database].findById(entityId);
  await entity[key].push({'fileName':fileName});
  entity.updatedAt = Date.now();
  await entity.save();
}

Answer №2

Consider implementing the following function in your code:

async function uploadImages(type, id, fileName) {
  const item = await db[type].findById(id);

  item.updated = Date.now();

  const attributeKey = `${type.toLowerCase()}Images`;
  item[attributeKey].push({ fileName });

  await item.save();
}

async function processUploads() {
  await uploadImages('Property', 2, 'image-02');
  await uploadImages('Account', 3, 'image-03');
  await uploadImages('Pet', 3, 'image-03');
}

You may also want to explore the Factory Pattern for creating reusable components.

If handling more variables, consider using an array for cleaner code. It is recommended to limit functions to three variables for better readability and maintainability, but this can vary based on personal preference.

Answer №3

Just utilize a single line of code for that task, there is no requirement to enclose it within a function

use db.Pet.updateOne({ _id: petId }, { $push: : { petImages : {'fileName':fileName}}, updated: Date.now() });

Answer №4

Appreciation to all who contributed comments and assistance.

The final version of my code is displayed below, although there is potential for further refinement.

async function addImagesToObject(objId, objType, fileName) {
  const entity = await db[`${objType}`].findById(objId);
  const attribute = `${objType.toLowerCase()}Images`; //<-- setting up selector
  await entity[attribute].push({'fileName':fileName});
  entity.updated = Date.now();
  await entity.save();
}

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

Generating content for List[case class]

There are 3 case classes in my code: scala> case class Friend(id: Long, hobbies: List[Long]) defined class Friend scala> case class Kid(friends: List[Friend]) defined class Kid scala> case class Parent(kids: List[Kid]) defined class Parent The ...

What steps are involved in setting up a sorting feature?

In order to utilize the array.sort() function, a number-returning function must be specified. Typically, it would look something like this: myArray.sort((item1, item2) => a < b); However, I am aiming for a different structure: myArray.sort(by(obj ...

Navigating through a website that loads content dynamically with AJAX can be easily done by

Having an issue with scraping data from a website using jQuery AJAX. There are 300 links to scrape, but the site only shows 50 at a time, requiring scrolling to load more. Can someone assist me with this? var baseURL = "https://hr.myu.umn.edu/psc/hrp ...

What is the best method for detecting null elements within an array?

Having numerous questions and answers in arrays, the unanswered questions need to be prioritized at the top with an error message. When a question is unanswered, the value in the array is stored as an undefined array element. My attempt to retrieve the po ...

Changing the color of a face in Three.js

I've been trying to change the color of a face, but I'm having trouble. When I use wireframe, it looks like it's working fine. However, when I don't use it, the face doesn't seem to render properly. var geo = new THREE.Geometry(); ...

Using the MongoDB aggregation pipeline to find and match the field name of a nested sub-document within a collection based on a reference model

In my possession are two collections: Product and Stores. product1 = { name: "chair", code: 034, }; product2 = { name: "table", code: 035, }; When material enters, the Stores model is updated with the following schema: goodsReceipt = { invoicenumber: ...

Enhance your JavaScript code with a custom push method polyfill

I was once asked in an interview if I could create a polyfill for the push() method in JavaScript. Does anyone have any tips on how this can be accomplished? ...

Creating Accurate JSON-LD Schema and Object Instance

, I am in the process of developing a graph database to describe power systems using JSON-LD for the first time. Here are the steps I've taken so far: - Created a schema following the guidelines provided in this documentation. - Saved the schema to t ...

Learn how to extract information from a MongoDB database and display it on a live webpage with the help of Node.js, React.js

Here is the data I obtained after running a query on the mongo terminal: db.contacts.find(); [ { _id: 59097d937386cc3a4e7b766b, name: 'Oreo', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca3bea9a38ca ...

ThreeJS Loading Page

Just starting out with ThreeJS and currently in the process of building a 3D Configurator. I'm looking to add a loading screen before the obj object loads, here's my current code: <!DOCTYPE html> </style> </head> <body& ...

Removing a value from an array using Jquery when an item is deselected from a dropdown

I'm currently facing a challenge in my project where I need to remove values from an array when they are unselected from a multi-select dropdown list. Adding values using push() works fine for me, but removing deselected values is proving to be more d ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

Using jQuery to create transitions when a class is changed and adding a delay to the transition

If you want to check out the section I created on CodePen, feel free to visit it by clicking here. I've noticed that my JavaScript code has a lot of repetitive elements and I'm looking to optimize it for better performance. Any advice on how I c ...

Unraveling AngularJS: Mastering the Art of Interpolating Interpol

Trying to interpolate a string retrieved from the database, such as "Users({{users_count || 0}})", poses a problem. Using {{}} or ng-bind for interpolation does not work properly. The HTML code written is {{data.usersCount}}, but instead of ren ...

Steps to extracting the JSON file from a pre-existing Google Map

I am looking to develop a customized Google Map search tool using the Google Maps API. I am curious if it is possible to extract the JSON data from a map created using the native Google Map management system, like this one: https://www.google.com/maps/d/v ...

Enhance the slider's worth

Hey there, just wanted to mention that I didn't write this code myself. Another person did, and I'm a bit lost trying to figure out how to assign values to the three sliders. I don't want a default value; I want each slider to take its value ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

Using Vue.js to dynamically calculate elapsed time

I am attempting to display the changing elapsed time from a specified start time <template> <div class="dashboard-editor-container"> <div class="wrapper__body"> <el-row :gutter="30"> <el-col v-fo ...

SyntaxError: Unexpected '<' symbol found in JavaScript file while attempting to import it into an HTML document

This issue is really frustrating me In my public directory, there is an index.html file Previously, I had a newRelic script embedded within the HTML in script tags which was functioning properly Recently, I moved the script to a separate JavaScript file ...

Search for a substring in JSON using Python

Currently, I am faced with the challenge of extracting two pieces of information from a lengthy JSON file using Python 2.7. The structure of the JSON data is as follows: { 'device': [ { 'serial': '00000000762c1d3c&apo ...