TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of that Friend entity would unexpectedly change to the user I was associating it with. Here's an example:

Before binding the Friend entity to any user object, its initial state looked like this:

Friend {
  id: '31466acb-749e-43f0-be82-4ec4c08d8ff5',
  createdAt: 2023-03-04T04:35:23.576Z,
  target: User {
    id: 3,
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4132202f2534012e34352d2e2e2a6f222e2c">[email protected]</a>',
    password: '$2a$10$/bVbxCmyFEfkPsqOvN0efePNLKYZjrFwfGJm1yTU3bICAS8q2MlcO',
    username: 'sandu',
    lastLoginAt: 2023-03-04T03:48:48.369Z,
    socketId: null,
    online: false
  }
}

However, after linking it to the user samzhangjy, the entity transformed into:

Friend {
  id: '31466acb-749e-43f0-be82-4ec4c08d8ff5',
  createdAt: 2023-03-04T04:35:23.576Z,
  target: User {
    id: 1,
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295a4844534148474e435069465c5d45464642074a4644">[email protected]</a>',
    password: '$2a$10$ibwq2hCq3pbzrEitlhEHjeP0H5wklkEmsjtQ.0ZMO3jLWOR4RhxXC',
    username: 'samzhangjy',
    lastLoginAt: 2023-02-25T04:28:29.079Z,
    socketId: 'CDWGfFWCskfH-J3RAAAD',
    online: true
  }
}

This unexpected behavior led to incorrect results when querying the friend lists of users.

The code snippet below showcases my service logic for adding friends:

// Service code here
// ...

I attempted to utilize both QueryBuilder and the .save method as shown in the code, but unfortunately, neither approach resolved the issue.

For reference, here is the structure of the Friend entity:

@Entity()
export class Friend {
  // Entity properties and relationships
}

And here is the structure of the User entity:

@Entity()
export class User {
  // Entity properties and relationships
}

Aside from this perplexing error involving the Friend.target property, everything else appears to be functioning correctly.

If anyone has insights or suggestions on how to address this issue, I would greatly appreciate the assistance. Thank you in advance!

Answer №1

If you've made changes to the entity relations, consider reloading it from the database before saving.

// Reload the user entity from the database before saving
sender = await this.userRepository.findOne(sender.id, {
  relations: ['friends', 'friends.target'],
});

// Save the user entity after reloading
await this.userRepository.save(sender);

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

Changing Angular 2 web app code to Ionic 2 mobile app code?

I currently have a web application code that was written using Angular 2. My goal is to create a hybrid mobile application by utilizing Ionic 2 for the same web application. Since Ionic 2 incorporates core concepts of Angular 2, I have a few questions: Is ...

What is the method to cancel an Observable subscription without having a reference to the object of type "Subscription"?

If I were to subscribe to an Observable without an object of type "Subscription," how can I properly unsubscribe from it? For instance, if my code looks something like this: this.subscription = bla ... I know I can easily unsubscribe using the following ...

I'm struggling to get a specific tutorial to work for my application. Can anyone advise me on how to map a general URL to the HTTP methods of an API endpoint that is written in C

I am struggling to retrieve and display data from a C# Web API using Typescript and Angular. As someone new to Typescript, I followed a tutorial to create a service based on this guide: [https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest- ...

Encountering issues with MongoDB $lookup function failing to retrieve accurate results

I'm a newcomer to MongoDB and currently attempting to retrieve all topics based on the subjectid and completestatus of a child from various collections. I am not achieving the desired results after using $lookup. Initially, I fetch all topic details ...

Guide to integrating an Angular 6/7 project as a dynamic plugin within a separate Angular 6/7 project

Currently embarking on a new project in Angular 7, however facing the challenge of incorporating 6 to 8 existing projects into this new platform dynamically as plugins. Your input on the feasibility and thoughts about this strategy would be greatly appreci ...

Typescript interface designed for objects containing certain optional property names as well as unspecified property names

I am looking to design an interface for an object that can have optional properties with specific names, as well as accept properties with arbitrary names. Here is my approach: interface CallBack { onTransition?(): any; // option A [key: string]: () = ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Show every item from a collection on individual lines within an Angular2 module

I am working with an Angular2 component that is responsible for displaying a list of speakers stored in some data. Currently, when I add the code below to my xyz.component.html, it shows the list as comma-separated strings. However, I would like each speak ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

Guide to packaging TypeScript type declarations with an npm JavaScript library

I'm facing an issue with providing TypeScript type definitions for a JavaScript library. The library itself is written in TypeScript and transpiled by Babel, although this detail shouldn't affect the outcome. The problem lies in the fact that ne ...

The efficiency of the Hive optimizer is lacking when it comes to handling joins with partitioned tables

I am currently utilizing Hive version 0.7.1-cdh3u2 In my database, I have two large tables known as A and B, both partitioned by day. I am executing the following query: select col1,col2 from A join B on (A.day=B.day and A.key=B.key) where A.day='20 ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...

React: a versatile and type-specific onChange() function

After adding as HTMLInputElement, the error message of Property 'checked' does not exist on type 'EventTarget & (HTMLInputElement | HTMLTextAreaElement)' is resolved. However, I find it interesting that TypeScript doesn't autom ...

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array. In this scenario, the 'items' ...

Replacing `any` in TypeScript when combining interfaces

Currently using Express and attempting to explicitly define res.locals. Issue arises as in the @types/express package, Express.Response.locals is declared as any, preventing me from successfully overwriting it: types/express/index.d.ts: declare namespace ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

How to Send TypeScript Object Excluding the '_id' Field?

I am currently developing a web app using Express, Mongoose, and Angular 2 (TypeScript). I want to post an instance of MyClass without including the _id field. In mongoose, the _id field is used for various operations in MongoDB. Here is how I have implem ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...