Search code examples
typescriptpostgresqlsequelize.jsnestjs

delete array of entities - postgres & nestjs with sequelize


this is my create function:

  async createDocument(createDocumentDto: CreateDocumentDto) {
    const request = await Document.build(<any>createDocumentDto);
    return await request.save();
  }

now im trying to delete the array of type CreateDocumentDto[] but i dont get from Document something like 'bulkDelete'

i've tried to do:

 const entities = await this.AnswersRepository.findAll(<any>deleteAnswerDto);
    if (!entities) {
      throw new NotFoundException(`Something went wrong, no changes applied!`);
    }
    return this.AnswersRepository.remove(entities);

but i got this error: "Property 'remove' does not exist on type 'typeof Answer'"

i can't find a solution to that. Would appreciate help :).


Solution

  • In your NestJS app, don't forget to configure routes and appropriately handle requests. Using Sequelize and NestJS, this code explains how to delete documents in bulk.

    In your DocumentService:

    @Injectable()
    export class DocumentService {
      async createDocument(createDocumentDto: CreateDocumentDto) {
        const document = await Document.build(createDocumentDto);
        return await document.save();
      }
    
      async deleteDocuments(documentIds: number[]) {
        return Document.destroy({
          where: {
            id: documentIds,
          },
        });
      }
    }
    

    In your DocumentController:

    @Controller('documents')
    export class DocumentController {
      constructor(private readonly documentService: DocumentService) {}
    
      @Delete()
      async deleteDocuments(@Body() documentIds: number[]) {
        await this.documentService.deleteDocuments(documentIds);
        return 'Documents deleted';
      }
    }