How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User.

The 'rating' field on the User Entity should be a mean calculation of all rating values from the Rating Entity, specifically the 'ratingValue' field.

To achieve this, the calculation for every User's 'rating' field should be as follows:

ratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length

The key fields involved here are 'ratingsReceived' on User:

  @OneToMany(
    () => Rating,
    rating => rating.ratingTo
  )
  ratingsReceived: Rating[];

And 'ratingValue' on Rating:

  @Column('decimal')
  @Min(0)
  @Max(5)
  ratingValue: number;

Answer №1

Through experimentation and testing, a solution was discovered to address this issue:

// This decorator is placed on the User Entity to execute after the entity loads in methods like find()
@AfterLoad()
  calculateRating = async () => {
    const result = await getRepository(Rating)
      .createQueryBuilder('ratings')
      .where('ratings."ratingToId" = :id', { id: this.id })
      .getRawAndEntities();

    const ratingsAboveZero = result?.entities?.filter(x => parseFloat(x.ratingValue));
    const count = ratingsAboveZero.length;

    if (count > 0) {
      this.rating =
        ratingsAboveZero.reduce((acc, curr) => {
          return acc + parseFloat(curr.ratingValue);
        }, 0) / count;

      this.ratingCount = count;
    } else {
      this.rating = 0;
      this.ratingCount = 0;
    }
  };

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

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Identify all elements that possess a specific attribute with a precise value in jQuery, and return either true or false

I'm having a slight issue with jQuery. Below is the code in question: if ($("select[rendelo='" + rendelo + "'][nap='" + nap + "'][napszak='" + napszak + "']").val() == 0) { alert('sth'); ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...

Perform a child component function in Angular

I'm working on a project with a child component as a map and a parent component as a form. The parent component has a field for writing the address, and when an address is entered, an HTTP request is triggered to find the latitude and longitude coordi ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

Utilizing the useEffect hook with outdated information

As I was learning about react hooks, I encountered a perplexing issue that I can't quite grasp. My goal is to create a list of numbers that can be incremented and should always display in descending order. However, when I input a high number initially ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

Every attempt to connect with the webservice via an ajax call has ended in failure

I am encountering an issue with a webservice call that I am making using jQuery's AJAX method. Despite receiving JSON data from the webservice when accessed directly through the browser, my site always triggers the error function rather than the succe ...

Utilizing Node Js for Form Data Transmission and Retrieval

I've successfully created two separate JS files, each responsible for sending and retrieving form data to and from the database. My dilemma is whether it's more practical or feasible to leave these two JS files as they are and serve their individ ...

Struggling to retrieve user input from a textfield using React framework

I'm having trouble retrieving input from a text-field in react and I can't figure out why. I've tried several solutions but none of them seem to be working. I even attempted to follow the instructions on https://reactjs.org/docs/refs-and-th ...

"Building a dynamic form with ReactJS, Redux Form, and Material UI - Implementing an

Currently working on a nested form framework that utilizes the redux form and material UI framework. The components have been developed up to this point - https://codesandbox.io/s/bold-sunset-uc4t5 My goal is to incorporate an autocomplete field into the ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Using Typescript to automatically infer strongly-typed recursive index types

Commencing with an Animal interface and a detailed map of animals residing on my farm: export interface Animal { species: string; edible: boolean; } export interface FarmMap{ [key: string]: Animal; } Everything seems to be running smoothly. Here ...

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Managing Multiple Operations in Angular Firestore

For the past few weeks, I've been grappling with the theory behind this issue. Despite scouring the internet for solutions, I haven't found anything truly helpful. So, I'm turning to the SO community for the first time. In my Firestore data ...