postgresqlsequelize.jsnestjssequelize-typescript

NestJS sequelize bulk insert


I am new to nestJS and I am trying to insert bulk data. But I get the following error and I can't seem to find what I am doing wrong here. Some guidance would be highly appreciated.

enter image description here

stockStyle.entity.ts file:

import {
  Column,
  ForeignKey,
  Model,
  Table,
  HasMany,
} from 'sequelize-typescript';
import { Stock } from '../stocks/entities/stock.entity';
import { Style } from '../styles/entities/style.entity';

@Table({ tableName: 'stock_style' })
export class StockStyle extends Model<StockStyle> {
  @ForeignKey(() => Stock)
  @Column
  stockId: string;

  @ForeignKey(() => Style)
  @Column
  styleId: number;
}

stockStyle.service.ts file:

import { Injectable } from '@nestjs/common';
import { StockStyle } from './v1/stockStyles/stockStyle.entity';

@Injectable()
export class StockStylesService {
  async bulkInsert() {
    const stockStyleArray = [
      { stockId: 'Diamond', styleId: 2 },
      { stockId: 'Gold', styleId: 2 },
      { stockId: 'Ruby', styleId: 2 },
    ];
    StockStyle.bulkCreate(stockStyleArray)
    
  }
}

Solution

  • I fixed it using the following way:

    async bulkInsert() {
    let holder: Array<StockStyle> = [];
    const stockStyleArray = [
      { stockId: '1', styleId: 1 },
      { stockId: '2', styleId: 1 },
      { stockId: '3', styleId: 1 },
    ];
    stockStyleArray.forEach((element) => {
      let stocks = new StockStyle();
      stocks.stockId = element.stockId;
      stocks.styleId = element.styleId;
      holder.push(stocks.get());
    });
    StockStyle.bulkCreate(holder);}
    

    I don't know if this is a vaiable solution or not. I just used a workaround here. If anyone has a solution or better alternative to this, then please do free to share the knowledge.