What’s the difference between remove and delete?

TypescriptTypeorm

Typescript Problem Overview


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?

Typescript Solutions


Solution 1 - Typescript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYegor ZarembaView Question on Stackoverflow
Solution 1 - TypescriptMukyuuView Answer on Stackoverflow