When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modification disappears.

Let's take a look at my Project Entity:

@ObjectType()
@Entity("project")
export class Project extends BaseEntity {
  @Field(() => Int)
  @PrimaryColumn()
  id: number;

  @Field()
  @Column("text")
  name: string;

  @Field({ nullable: true })
  @Column("text", { nullable: true })
  cluster?: string;
  
  //project_groups
  @ManyToMany(type => Group, group => group.projects, { lazy: true })
  @Field(type => [Group], { nullable: true })
  @JoinTable()
  groups?: Group[];
}

Now, let's examine my Group Entity:

@ObjectType()
@Entity("group")
export class Group extends BaseEntity {
  @Field(() => String)
  @PrimaryColumn()
  id: string;

  @Field()
  @Column("text")
  name: string;

  @Field({ nullable: true })
  @Column("text")
  type: string;

  @Field({ nullable: true })
  @Column("text", { nullable: true })
  currency: string;

  @Field(type => [Project])
  @ManyToMany(type => Project, project => project.groups, { lazy: true })
  projects: Project[];

  //group_modifiers
  @ManyToMany(type => Modifier, modifier => modifier.group, { lazy: true })
  @Field(type => [Modifier])
  @JoinTable()
  modifiers: Modifier[];
}

If I introduce a new field to either the Group or the Project, an automatic migration takes place running the following queries:

query: CREATE TABLE "temporary_project" ("id" integer PRIMARY KEY NOT NULL, "name" text NOT NULL, "cluster" text, "asdfa" text)
query: INSERT INTO "temporary_project"("id", "name", "cluster") SELECT "id", "name", "cluster" FROM "project"
query: DROP TABLE "project"
query: ALTER TABLE "temporary_project" RENAME TO "project"

Shouldn't the relationship table retain the existing data?

Answer №1

Using the synchronize option is recommended during development stages when frequent changes are being made to the data model, but it should be disabled before deployment.

The synchronize option determines whether the database schema is automatically created each time the application is launched. It is advised not to enable this option in production as it may result in the loss of important data. This feature is most useful for debugging and development purposes. Alternatively, the schema:sync command can be used via CLI.

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

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

Does the JavaScript Amazon Cognito Identity SDK offer support for the Authorization Code Grant flow?

Is there a way to configure and utilize the Amazon Cognito Identity SDK for JavaScript in order to implement the Authorization Code Grant flow instead of the Implicit Grant flow? It appears that the SDK only supports Implicit Grant, which means that a Clie ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

Vue3 can accept a prop of type String or PropType

In my Vue3 project, I have a component that accepts a prop which can be either a string or an object. Here's how it looks: import { defineComponent } from 'vue' const Component = defineComponent({ props: { book: { type: [String, ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

Oops! An issue occurred during the `ng build` command, indicating a ReferenceError with the message "Buffer is not defined

I'm facing an issue while trying to utilize Buffer in my angular component ts for encoding the Authorization string. Even after attempting npm i @types/node and adding "node" to types field in tsconfig.json, it still doesn't compile with ng buil ...

Unable to position text in the upper left corner for input field with specified height

In a project I'm working on, I encountered an issue with the InputBase component of Material UI when used for textboxes on iPads. The keyboard opens with dictation enabled, which the client requested to be removed. In attempting to replace the textbox ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source. The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload. I have confirmed ...

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

Exploring URL Parameters in Angular Unit Testing

My goal is to execute a test to check for the presence of a specific string in URL parameters. Inside my TypeScript file, I have defined the following method: checkURLParams() { if (this.route.parent) { this.route.parent.params.subscribe((params) ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

Implementing a Set polyfill in webpack fails to address the issues

Encountering "Can't find variable: Set" errors in older browsers during production. Assumed it's due to Typescript and Webpack leveraging es6 features aggressively. Shouldn't be a problem since I've successfully polyfilled Object.assign ...

Using Datatable.net with Angular 6 for Change Monitoring

I've been encountering several issues with the custom datatable component that I created. One specific problem is that when I delete a row from my datatable, not only does the row disappear, but also the pagination functionality and other features st ...