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
removeif it contains an array of Entities.While you should use
deleteif 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 OverflowHow to delete many rows typeorm - postgresql & node.js(typescript) - Stack Overflow
Unable to delete entire table using Repository/EntityManager API
TypeORM documentation delete ManyToMany
Delete & Update applies to all entities in table if criteria is undefined or empty
If your table has a single ID column then you should be able to pass an array of IDs:
await EmployeeAnswers.delete(ids.employeeAnswersIds);
You could also specify multiple IDs in your where clause using In:
await EmployeeAnswers.delete({ id: In(ids.employeeAnswersIds) });
However if you deal with a table that has a composite primary key, like in my case, the following example can be the solution for you. I'm not crazy about this answer, but here is how I overcame this problem using DeleteQueryBuilder (docs):
async remove(ids: DeleteEmployeeAnswerDTO): Promise<boolean> {
if (ids.employeeAnswersIds.length) {
const deleteQueryBuilder = EmployeeAnswer.createQueryBuilder().delete()
const idClauses = ids.map((_, index) => `ID = :id${index}`)
const idClauseVariables = ids.reduce((value: any, id, index) => {
value[`id${index}`] = id
return value
}, {})
await deleteQueryBuilder.where(idClauses.join(' OR '), idClauseVariables).execute()
}
return true;
}
You can search for multiple records and then delete the entities found in a single operation. If one or more entities are not found, then nothing is deleted.
async removeMany(ids: string[]) {
const entities = await this.entityRepository.findByIds(ids);
if (!entities) {
throw new NotFoundException(`Some Entities not found, no changes applied!`);
}
return this.entityRepository.remove(entities);
}
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.
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
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();
});