What’s the difference between remove and delete?

Yegor Zaremba picture Yegor Zaremba · Jan 18, 2019 · Viewed 32.6k times · Source

For example, I have a TypeORM entity Profile:

@Entity()
class Profile {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    gender: string;

    @Column()
    photo: string;

    @OneToOne(type => User, { cascade: true })
    @JoinColumn()
    user: User;
}

And I’m not sure which one should I use to delete a user profile?

Profile.remove(profile)
Profile.delete(profile)

What is the difference between the remove and delete methods in TypeORM?

Answer

Mukyuu picture Mukyuu · Jan 18, 2019

From Repo:

  • remove - Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional).

Example:

await repository.remove(user);
await repository.remove([
    category1,
    category2,
    category3
]);
  • delete - Deletes entities by entity id, ids or given conditions:

Example:

await repository.delete(1);
await repository.delete([1, 2, 3]);
await repository.delete({ firstName: "Timber" });

As stated in example here:

import {getConnection} from "typeorm";

await getConnection()
    .createQueryBuilder()
    .delete()
    .from(User)
    .where("id = :id", { id: 1 })
    .execute();

Which means you should use remove if it contains an array of Entities.

While you should use delete if you know the condition.


Additionally, as @James stated in comment Entity Listener such as @BeforeRemove and @AfterRemove listeners only triggered when the entity is removed using repository.remove.

Similarly, @BeforeInsert, @AfterInsert, @BeforeUpdate, @AfterUpdate only triggered when the entity is inserted/updated using repository.save.

Source: Entity Listeners and Subscribers