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.
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)
}
}
CodePudding user response:
StockStyle.bulkCreate([ stockStyleArray])
I`m not sure, but you should try
StockStyle.bulkCreate(stockStyleArray)
CodePudding user response:
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.