typeorm: Saving with Many-to-Many relation and { cascade: true } causes duplicate key error

Issue Description

Hi, I’m encountering a problem on a fairly simple use case, but I’m still not sure if it’s a bug, a misunderstanding on my part, or just the expected behavior. If it’s not a bug, maybe some details are missing in the documentation because I’ve gone through it in detail.

I have 2 entities (Game and Category) linked with a Many-to-Many relation :

@Entity()
export class Game {
  @PrimaryColumn()
  id: number;

  @PrimaryColumn()
  name: string;

  @ManyToMany(
    () => Category,
    category => category.games,
    { eager: true, cascade: true } // Notice de cascade: true option
  )
  @JoinTable()
  categories: Category[];
}
@Entity()
export class Category {
  @PrimaryColumn()
  id: number;

  @PrimaryColumn()
  name: string;

  @ManyToMany(
    () => Game,
    game => game.categories
  )
  games: Game[];
}

I load my initial data by scraping some information on a website, which is like doing the following sequence:

// This is the data i am scraping around (in real life, I get one game at a time)
const games = [
  {
    id: 1,
    name: 'Game 1',
    categories: [
      {
        id: 1,
        name: 'Category 1'
      },
      {
        id: 2,
        name: 'Category 2'
      }
    ]
  },
  {
    id: 2,
    name: 'Game 2',
    categories: [
      {
        id: 1,
        name: 'Category 1'
      }
    ]
  }
]

// And I try to save them in the database as follows (simplified syntax):
games.forEach(g => {

  const game = new Game()
  game.id = g.id;
  game.name = g.name

  item.categories.forEach(c => {

    const category = new Category()
    category.id = c.id
    category.name = c.name

    game.categories.push(category)
  })

  gamesRepository.save(game)
})

With this approach, Game 1 is saved in db with its 2 relations and Category 1 and Category 2 are created because they did not exist in the categories table (according to cascade: true option), but when it comes to saving Game 2, the cascading process tries to re-create Category 1, although it already exists, which leads to a duplicate key error.

Shouldn’t TypeORM see that Category 1 already exists and not try to insert it ?

Expected Behavior

When saving Game 2, I expect the save operation to save both game and relation, but not to try to insert an other Category 1, as it already exists.

Actual Behavior

When saving Game 2, the save operation tries to insert Category 1 again, resulting in a duplicate key error:

error: error: duplicate key value violates unique constraint "PK_7e79a17df5fe348e5f8868a75ae"
    at Connection.parseE (/Users/guillaumemartin/Projects/GM/boardgameblink/node_modules/pg/lib/connection.js:581:48)
    at Connection.parseMessage (/Users/guillaumemartin/Projects/GM/boardgameblink/node_modules/pg/lib/connection.js:380:19)
    at TLSSocket.<anonymous> (/Users/guillaumemartin/Projects/GM/boardgameblink/node_modules/pg/lib/connection.js:116:22)

My Environment

Dependency Version
Operating System MacOS 10.13.6
Node.js version v12.13.0
Typescript version v3.8.3
TypeORM version v0.2.24
NestJS version v7.0.0

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 9
  • Comments: 16

Most upvoted comments

Any updates? faced with the same issue

Having the same issue

Out of interest, can you tell me how you switched the join table key type?

In fact I did not modify the join table key type, what I meant is that instead of having 2 @PrimaryColumns in my models I kept only one (the id). The name attribute becoming a regular @Column. I thought that might be what prevented TypeORM from finding the already existing Category.