yonycalsin / nestjs-sequelize-seeder Goto Github PK
View Code? Open in Web Editor NEW๐พ A simple extension library for nestjs sequelize to perform seeding.
Home Page: https://www.npmjs.com/package/nestjs-sequelize-seeder
License: MIT License
๐พ A simple extension library for nestjs sequelize to perform seeding.
Home Page: https://www.npmjs.com/package/nestjs-sequelize-seeder
License: MIT License
Hi i'm getting this error from time to time when my nestjs project is reloading due to changes in the code. I run it in watch mode locally so it reloads the seeder everytime so I have data to debug.
Here is the error, made it more generic, but it basically says that the Foreign Key ID in the table I want to reference does not exist yet:
[Seeder] [ERROR...] Cannot add or update a child row: a foreign key constraint fails (database
.Table1
, CONSTRAINT Constraint_ibfk_1
FOREIGN KEY (ForeignKeyId
) REFERENCES Table2
(id
) ON DELETE NO ACTION ON UPDATE CASCADE)
E.g.:
Loading cat row into db before the row for breedId 2 has been loaded results in the error above.
First loaded
Cat: {
id = 1;
breedId = 2;
}
Loaded second
Breed: {
id = 2;
name = persian;
}
It can also be the order, of the execution.
For example, when sequelize returns an error, when creating a new object for your model, there the id will increase, therefore the added associations will not match.
First you will have to execute the tables in their proper order, for example, if you create a breed
and cat
table, and associate it, then you will have to execute the breed
table first and then cat
, since the cat
table depends on the breed
table.
With nestjs it's easy to sort, the modules.
Module({
imports: [
// First
BreedModule,
// Second
CatModule,
],
});
class AppModule {}
For the 'Breed' seed
const data = [
{
// Here don't forget to add the id
id: 1,
name: 'persian',
},
];
For the 'Cat' seed
const data = [
{
// You'll also have to add an id, to save us some trouble
id: 1,
breedId: 1,
},
];
I hope this helps you!
Originally posted by @yoicalsin in #12 (comment)
@yoicalsin
I'd also like to point out i'm using a junction table for my CatBreed many-to-many relation. I'm having some issues with this as well. The db cant find the FK relation id's of the Cat & Breed models (example: catId, breedId).
This worked perfectly in v1.0.7 of "nestjs-sequelize-seeder"
At the moment those error logs have stopped appearing after playing around with the settings, not sure if it's still there or not. Just going to mention it anyway.
Here is my junction table seeder:
@Seeder({
unique: [],
model: CatBreed
})
export class SeedCatBreeds implements OnSeederInit {
run() {
return [
{id: 1, catId: 1, breedId: 1},
{id: 2, catId: 1, breedId: 4},
{id: 3, catId: 2, breedId: 2},
{id: 4, catId: 2, breedId: 3},
] as CatBreed[];
}
}
my junction table model:
@Table
export class CatBreed extends Model<CatBreed> {
@PrimaryKey
@AutoIncrement
@Column
id: number;
@ForeignKey(() => Breed)
@Column
breedId: number;
@BelongsTo(() => Breed)
breed: Breed;
@ForeignKey(() => Cat)
@Column
catId: number;
@BelongsTo(() => Cat)
cat: Cat;
}
@Seeder({
model: Cat,
unique: ['name'], // -> this gives an error:
// Error: [SeederService] Unknown column 'CatBreed.name' in 'where clause'
})
export class SeedCats implements OnSeederInit {
run() {
return [
{
id: 1,
name: 'Mr Mistofeles',
},
]
}
}
Unhandled rejection SequelizeUniqueConstraintError: Validation error
at Query.formatError (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/sequelize/lib/dialects/mysql/query.js:223:16)
at Execute.handler [as onResult] (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/sequelize/lib/dialects/mysql/query.js:51:23)
at Execute.execute (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/commands/command.js:30:14)
at Connection.handlePacket (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:417:32)
at PacketParser.onPacket (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:75:12)
at PacketParser.executeStart (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/packet_parser.js:75:16)
at Socket.<anonymous> (/mnt/b020cfba-0b36-4fcc-b0d7-3edea52ca1b3/courses/nestjs-course/node_modules/mysql2/lib/connection.js:82:25)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Unhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`animals`.`CatBreeds`, CONSTRAINT `CatBreeds_ibfk_1` FOREIGN KEY (`catId`) REFERENCES `Cats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
I think this error is caused due to the "cat" that needs to be referenced isn't loaded yet.
I've kept an eye in terms of order of loading modules & seeders where the ones with FK's get loaded last.
So that's not the issue I think.
I've also deleted the database as well.
SequelizeModule.forRootAsync({
useFactory: () => {
return {
...
autoLoadModels: true,
synchronize: true,
sync: {
force: true,
},
...
};
},
}),
SeederModule.forRoot({
isGlobal: true,
logging: true,
connection: 'animals',
}),
"nestjs-sequelize-seeder": "~1.0.9",
"sequelize": "^5.21.6",
"sequelize-cli": "^5.5.1",
"sequelize-typescript": "^1.1.0",
"@nestjs/sequelize": "^0.1.0",
"@types/sequelize": "^4.28.8",
"mysql2": "^2.1.0",
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.