Saving new row in database deletes previous row

Viewed 51

I have a products Entity like:

@Entity('products')
    export class productsEntity extends BaseEntity{
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column({nullable: false, unique: true})
        title: string;
    
        //..other columns
    
        @Column({type:"integer", nullable: false})
        units: number;
    
        @ManyToMany( () => categoryEntity, category => category.products, {eager: true,})
        @JoinTable( {name:"products_categories",
                    joinColumn: {name: 'productId', referencedColumnName: 'id'},
                    inverseJoinColumn: {name: 'categoryId', referencedColumnName:'id'}
                  })
        categories: categoryEntity[];
    }

Then i also have a categories Entity:

@Entity('categories')
export class categoryEntity extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

    @Column({nullable: false, default: 'all', unique: true})
    title: string;
    
    @ManyToMany(()=> productsEntity, product => product.categories)
    products: productsEntity[];
}

These two have many to many relationship between them. This is the function i am using to create a new product and save.

async addProduct(productDetails: productsEntity, username, categor: categoryEntity){
        const {title, description, price, units}  = productDetails;
        try{ 
            let newProduct = new productsEntity();
            newProduct.title = title;
            newProduct.description = description;
            newProduct.price = price;
            newProduct.units = units;
            newProduct.soldBy = username;
           
            newProduct.categories = newProduct?.categories ?? [];
            newProduct.categories.push(categor);
            categor.products= categor?.products?? [];
            categor.products.push(newProduct);
            await newProduct.save();
            await categor.save();
            
        }
        catch(err){
            this.logger.error(err.message);
            throw new HttpException('Failed adding Product.', HttpStatus.INTERNAL_SERVER_ERROR)
        }
    }

Whenever a new product is inserted the previous row gets deleted in the junction table. Example:

 productId | categoryId
-----------+------------
         8 |          2
        24 |          1

This gets updated instead of making a new row for a new product if i add with an existing category id. like this

 productId | categoryId
-----------+------------
         8 |          2
        25 |          1

I dont understand whats wrong with this.

0 Answers
Related