Search code examples
typescriptmany-to-manynestjstypeorm

Many to Many TypeOrm NestJs Save


I have a problem how to save in NestJs with TypeORM Many to Many relationships. I try to push will only be in responsive and will not save in joinTable id of cat and of book. Thanks!

service.ts

async addBookToCat(catId: string, bookId: string): Promise<any> {

    const cat =  await this.catRepository.findOne(catId);
    if(!cat) {
      throw new NotFoundException('Category not found!');
    }
    const book = await this.bookRepository.findOne(bookId);
    if(!book) {
      throw new NotFoundException('Book not found!');
    }
    cat.book.push(book);
    return cat; 
  }

Category.entity.ts

  @ManyToMany(type => Book, book => book.cat, {eager: true})
  @JoinTable()
  book: Book[];

Book.entity.ts

  @ManyToMany(type => Category, cat => cat.book, {eager: false, cascade: true})
  cat: Category[];

Solution

  • You forgot save result

    ...
    cat.book.push(book);
    return this.catRepository.save(cat);