The Connection Between TypeORM Entities

I am hoping to streamline the process and avoid the need for a second database query when saving a row with a relationship. Users have the ability to create multiple events, and each user must go through authentication, allowing me access to their userID. I'm contemplating whether creating a relationship based on a specific User ID field would be more efficient than using the entire User object.

The structure of the Entity is as follows:

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  JoinColumn,
  ManyToOne,
} from 'typeorm';
import { User } from './User';

@Entity()
export class Event {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  eventName: string;

  @ManyToOne(() => User)
  @JoinColumn()
  createdBy: User;
}

export default Event;

Here is how it's handled in the Controller:

const userRepository = AppDB.getRepository(User);
const EventRepository = AppDB.getRepository(Event);

export async function addEvent(userID: number, eventObject: EventObject) {
  const u = await userRepository.findOneByOrFail({ id: userID }); //Considering removing this line <---
  const e = new Event();
  Object.assign(e, eventObject);
  e.eventStart = new Date(eventObject.eventStart);
  e.eventEnd = new Date(eventObject.eventEnd);
  e.createdBy = u; //Possibly simplifying to e.createBy = userID. <----
  await EventRepository.save(e);
  return e;
}

Answer №1

Although I have not had the opportunity to test this method personally, one way to approach it would be by assigning a specific name to the JoinColumn and creating a corresponding column with that name. This eliminates the need to retrieve the entity each time, as setting the id alone should suffice.

@ManyToOne(() => User)
  @JoinColumn({name: 'assignedUserId'})
  assignedUser: User;

  @Column()
  assignedUserId: number; // make sure to use the appropriate type for the primary key of the User's entity
const TaskRepository = AppDB.getRepository(Task);

export async function addTask(userID: number, taskObject: TaskObject) {
  const t = new Task();
  Object.assign(t, taskObject);
  t.taskStart = new Date(taskObject.taskStart);
  t.taskEnd = new Date(taskObject.taskEnd);
  t.assignedUserId = userID;
  await TaskRepository.save(t);
  return t;
}

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

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Utilizing React with Typescript to create JSX text translation files

My task involves translating text stored in a file... ///translations.txt const TEXT: { [x: string]: { [y: string]: string } } = { en: { joinNow: <React.Fragment>Join <b>Now<b/></React.Fragment>, signUp: <React.Fragmen ...

Are you looking for room migrations with updates triggered by AFTER INSERT ON events?

My application is designed for testing outlets to ensure they have the correct voltage output. I am currently using Room Database and working on migrating from Version 1 to Version 2 of the database with a custom room migration. The challenge I encountere ...

Is it possible for me to assign a general data type to a function that duplicates an item while adding or changing a key with a different value?

In my recent coding endeavor, I've crafted the following function: function extend(obj, key, value) { return { ...obj, [key]: value } } Ideally, I want to utilize this function in a versatile manner, with obj representing an Object of which the t ...

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

Encountering the following issue: "ERROR TypeError: Argument is required in IE 11"

The code below is functioning properly in all internet browsers except for IE11. When running the code in IE, an error is thrown stating "ERROR TypeError: Argument not optional." The project being developed is using Angular 10. private togglePageClass(mod ...

How can I alter the appearance of HTML text when hovering over the enclosing div?

I want the text to change color and zoom when the cursor is near it (when the mouse enters the area of the div containing the text). Currently, I am able to change the text color only when hovering directly over it. Below is a snippet of the code. HTML: & ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Angular httpClient: Adjusting date format within json object

I need help converting the date property of an object to a format that the server can understand when using httpClient.post(...). Currently, the date property has its natural string representation. What steps can I take to make sure it is in the correct ...

Incapable of acquiring the classification of the attribute belonging to the

Is it possible to retrieve the type of an object property if that object is stored in a table? const records = [{ prop1: 123, prop2: "fgdgfdg", }, { prop1: 6563, prop2: "dfhvcfgj", }] const getPropertyValues = <ROW extends o ...

Encountering an issue - Verify that the Cursor has been properly initialized prior to retrieving data from it

When trying to retrieve data from SQLite, I encountered the following exception: 11-19 11:37:43.357: E/AndroidRuntime(1494): java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly ...

Tips for utilizing the useEffect hook to update a state while avoiding an endless cycle of re-renders

I currently have the following state: const [doctor, setDoctor] = useState<doctorStateProps | null>(null) And then I implemented a useEffect function like this: useEffect(() => { if(!doctor){ axios.get(`doctor/${id}`).then(({d ...

The new experimental appDir feature in Next.js 13 is failing to display <meta> or <title> tags in the <head> section when rendering on the server

I'm currently experimenting with the new experimental appDir feature in Next.js 13, and I've encountered a small issue. This project is utilizing: Next.js 13 React 18 MUI 5 (styled components using @mui/system @emotion/react @emotion/styled) T ...

Why does the playwright's onEnd() results not include the duration as specified in the documentation? What am I overlooking?

The built-in onEnd method can have a results object that is accessible within the function. According to the documentation here, this object should include the property duration, which represents the time in milliseconds. However, when I attempt to access ...

Typescript error encountered in customized PipeLine class

I am currently developing a web scraping application using Puppeteer. In this project, I aim to create a PipeLine class that will take the current instance of the page and expose an add method. This add method should accept an array of functions with the t ...

Utilizing Node, Jade, Express, and Sqlite: Implementing a MiniMap on a Leaflet Map

I recently created a map using Node, Jade, Express, and Sqlite. I am now attempting to incorporate a minimap using a plugin, but the function I added does not seem to be working correctly. Below is the code snippet that I have been working with: In my HTM ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

I am looking to store a collection of objects in Firebase using a single request, and I want Firebase to generate a unique key for each object without using array

I am looking to store a set of objects in Firebase using a single request with a unique key generated by Firebase (without using array indexes as keys). let object_list = { '0': { 'title':'title 1', 'time&apos ...

Updating an array of numbers in Mongoose: A guide

I am having trouble updating an array within a MongoDB document using Mongoose. Below is my stock model definition: const ticker = new mongoose.Schema({ ticker: String, Price: Number, Amount: Number, PastPrices: [Number] }); export const stock ...

Using React hooks with Material-UI: Snackbar displaying only on first occasion and not again

I have identified an issue that can be easily reproduced. Steps to replicate: Step 1: Start a react app and include material-ui in the project: prompt> create-react-app mui-test prompt> cd mui-test prompt> yarn add @material-ui/core @material-ui ...