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

Answer from Mukyuu on Stack Overflow
🌐
TypeORM
typeorm.io › delete using query builder
Delete using Query Builder | TypeORM
TypeORM 1.0 is here! Check the release notes and upgrading guide. ... You can create DELETE queries using QueryBuilder.
Discussions

How to delete many rows typeorm - postgresql & node.js(typescript) - Stack Overflow
Hi friends this is my function, it gets an array of ids I want to erase the rows in one stroke and not run in the loop, and can't find a solution to that. Would appreciate help. async remove(ids: More on stackoverflow.com
🌐 stackoverflow.com
Unable to delete entire table using Repository/EntityManager API
The new version throws the following error: Empty criteria(s) are not allowed for the delete method. ... This behavior was consistent with TypeORM’s API as well as with the API of other libraries across the Node.js ecosystem. More on github.com
🌐 github.com
10
August 5, 2025
TypeORM documentation delete ManyToMany
What you're missing is a good orm written by competent people. That dude pleerock who's charged with maintaining typeorm just doesn't care anymore. Mikroorm is a great alternative with solid documentation, consistent behavior (i.e., no bugs rebranded as features - this is an actual problem with typeorm) and active maintainers More on reddit.com
🌐 r/typescript
15
12
August 8, 2021
Delete & Update applies to all entities in table if criteria is undefined or empty
There was an error while loading. Please reload this page More on github.com
🌐 github.com
12
February 28, 2018
🌐
Medium
jimkang.medium.com › typeorm-delete-multiple-records-6119ff8b740
Typeorm delete multiple records. this is just a quick note (for myself)… | by Jim Kang | Medium
September 1, 2020 - Typeorm delete multiple records this is just a quick note (for myself) on how to delete / remove multiple row using typeorm since it’s hard to search from the top results
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Reddit
reddit.com › r/typescript › typeorm documentation delete manytomany
r/typescript on Reddit: TypeORM documentation delete ManyToMany
August 8, 2021 -

Hi.

I followed the official documentation at TypeORM and came to the following section.

https://typeorm.io/#/many-to-many-relations

Deleting many to many:

const question = getRepository(Question); question.categories = question.categories.filter(category => { category.id !== categoryToRemove.id }) await connection.manager.save(question)

According to the documentation this should delete the categories and questions connection from the joint table. But whenever I try to follow along I get Property 'categories' does not exist on type 'Question[]'. error showing.

I have followed the documentation to a T, 100% the same, but that error shows up anyway.

What am I missing here?

Thanks.

🌐
Gitbook
sparklytical.gitbook.io › typeorm › query-builder › delete-using-query-builder
Delete using Query Builder - TypeOrm - GitBook
January 24, 2021 - You can create DELETE queries using QueryBuilder. Examples: Copy · import {getConnection} from "typeorm"; await getConnection() .createQueryBuilder() .delete() .from(User) .where("id = :id", { id: 1 }) .execute(); This is the most efficient way in terms of performance to delete entities from your database.
Find elsewhere
🌐
GitHub
gist.github.com › proclaim › 63c2dedf4d1cf40dc4f5460a7d74c2d2
typeorm delete multiple records · GitHub
This "...ids" is not "SQL" right ? it's seem like JS expression, So it's allowed to put expression there ? I agree, not sure you can run the spread operator in that string since it will get translated to sql · getConnection() .createQueryBuilder() .delete() .from(entity) .where('id In(:id)', { id: ['1','2'], }) .execute();
🌐
GitHub
github.com › typeorm › typeorm › issues › 1680
Delete & Update applies to all entities in table if criteria is undefined or empty · Issue #1680 · typeorm/typeorm
February 28, 2018 - typeorm / typeorm Public · There was an error while loading. Please reload this page. Notifications · You must be signed in to change notification settings · Fork 6.5k · Star 36.3k · New issueCopy link · New issueCopy link · Closed · Closed · Delete & Update applies to all entities in table if criteria is undefined or empty #1680 ·
Author   typeorm
🌐
StudyRaid
app.studyraid.com › en › read › 10725 › 326737 › deleting-database-entries
Understand deleting database entries
December 19, 2024 - Cascade deletions automatically remove related entities when deleting a parent entity. Configure cascading in entity relationships: ... @Entity() class User { @OneToMany(() => Post, post => post.user, { cascade: ['remove'] }) posts: Post[]; } For removing multiple records simultaneously, TypeORM provides efficient bulk deletion methods:
🌐
GitHub
github.com › typeorm › typeorm › issues › 6620
Here is how you can quickly delete an entire table. Is this a bug or a feature? · Issue #6620 · typeorm/typeorm
August 26, 2020 - (typeorm 0.2.18) When you want to count or select something, here is how you do it: manager.count(Entity, { where: { value: In(values), } }); When you want to delete something: this works fine - manager.delete(Entity, { value: In(values), }); this ...
Author   typeorm
🌐
TypeORM
typeorm.biunav.com › en › delete-query-builder.html
Delete using Query Builder | TypeORM Docs
await myDataSource .createQueryBuilder() .delete() .from(User) .where("id = :id", { id: 1 }) .execute()
🌐
YouTube
youtube.com › watch
Fullstack2021 | p67 | TypeOrm | Find all and delete using id
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Doug-martin
doug-martin.github.io › nestjs-query › docs › persistence › typeorm › soft-delete
Soft Delete | Nestjs-query
import { QueryService } from '@nestjs-query/core';import { TypeOrmQueryService } from '@nestjs-query/query-typeorm';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { TodoItemEntity } from './todo-item.entity'; @QueryService(TodoItemEntity)export class TodoItemService extends TypeOrmQueryService<TodoItemEntity> { constructor(@InjectRepository(TodoItemEntity) repo: Repository<TodoItemEntity>) { // pass the use soft delete option to the service. super(repo, { useSoftDelete: true }); }}Copy · Notice that when calling super the useSoftDelete option is set to true. This will ensure that all deletes use the softRemove when deleting one or softDelete when deleting many.
🌐
Tripss
tripss.github.io › soft delete
Soft Delete | Nestjs-query
Notice that when calling super the useSoftDelete option is set to true. This will ensure that all deletes use the softRemove when deleting one or softDelete when deleting many.
Top answer
1 of 5
21

Maybe a little late but was searching for this as well, this is what I came up with.

This will only delete the content inside the entities, not the entities itself.

afterEach(async () => {

    // Fetch all the entities
    const entities = getConnection().entityMetadatas;

    for (const entity of entities) {
        const repository = getConnection().getRepository(entity.name); // Get repository
        await repository.clear(); // Clear each entity table's content
    }
});

EDIT: If you're using foreign keys, make sure to add the {onDelete: "CASCADE"} property to your columns in order to delete all the records correctly.

More information about that can be found here: https://github.com/typeorm/typeorm/issues/1460#issuecomment-366982161

2 of 5
7

Here is a simple and efficient way to fully clean a DB with typeorm, in creating a dedicated TestService which TRUNCATE all entities in one command:

import { Inject, Injectable } from "@nestjs/common";
import { Connection } from "typeorm";

@Injectable()
export class TestService {
  constructor(@Inject("Connection") public connection: Connection) {}

  public async cleanDatabase(): Promise<void> {
    try {
      const entities = this.connection.entityMetadatas;
      const tableNames = entities.map((entity) => `"${entity.tableName}"`).join(", ");
      
      await this.connection.query(`TRUNCATE ${tableNames} CASCADE;`);
      console.log("[TEST DATABASE]: Clean");
    } catch (error) {
      throw new Error(`ERROR: Cleaning test database: ${error}`);
    }
  }
}

Then you can call this function in your testing files:

beforeEach(async () => {
  await testService.cleanDatabase();
});

🌐
GitHub
github.com › typeorm › typeorm › issues › 999
Update/remove all with auto-completion · Issue #999 · typeorm/typeorm
typeorm / typeorm Public · Notifications · You must be signed in to change notification settings · Fork 6.4k · Star 35.3k · New issueCopy link · New issueCopy link · Closed · Closed · Update/remove all with auto-completion#999 · Copy link · Assignees ·
Author   typeorm
🌐
Medium
john-hu.medium.com › typeorm-deletes-one-to-many-orphans-a7404f922895
TypeORM deletes one-to-many orphans | by John Hu | Medium
August 31, 2023 - We know we must delete the orphaned child entities when we link different entities to the parent. It’s easy to delete them with the SQL command, like DELETE FROM order_detail WHERE ID in (?, ?, ?). Since we entered the OR-mapping world, may we benefit from the OR-mapping? Let’s try it with the TypeORM!
🌐
GitHub
github.com › typeorm › typeorm › blob › master › test › functional › repository › clear › repository-clear.ts
typeorm/test/functional/repository/clear/repository-clear.ts at master · typeorm/typeorm
November 6, 2020 - ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms. - typeorm/test/functional/repository/clear/repository-clear.ts at master · typeorm/typeorm
Author   typeorm