We need to create seed data for our Superheros database table. This involves:
Looking at existing models and migrations to understand the data structure, then creating valid seed data that meets all constraints and validations. Think of this like preparing a garden - we need to plant the right seeds in the right way for our database garden to grow properly.
First, let's examine our Superhero model constraints (typically found in models/superhero.js):
// Example model structure we need to satisfy:
{
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
alias: {
type: DataTypes.STRING,
unique: true
},
powerLevel: {
type: DataTypes.INTEGER,
validate: {
min: 1,
max: 100
}
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true
}
}
File: seeders/20220413205503-valid-superheros.js
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
// Define our seed data
const validSuperheros = [
{
name: 'Peter Parker',
alias: 'Spider-Man',
powerLevel: 85,
active: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
name: 'Bruce Wayne',
alias: 'Batman',
powerLevel: 70,
active: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
name: 'Diana Prince',
alias: 'Wonder Woman',
powerLevel: 95,
active: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
name: 'Clark Kent',
alias: 'Superman',
powerLevel: 100,
active: true,
createdAt: new Date(),
updatedAt: new Date()
},
{
name: 'Tony Stark',
alias: 'Iron Man',
powerLevel: 88,
active: true,
createdAt: new Date(),
updatedAt: new Date()
}
];
// Insert the seed data
return queryInterface.bulkInsert('Superheros', validSuperheros, {});
},
down: async (queryInterface, Sequelize) => {
// Remove all seeded data
return queryInterface.bulkDelete('Superheros', null, {});
}
};
To verify our seeding implementation:
npx sequelize-cli db:seed:allnpm testDatabase seeding is crucial in real-world applications for:
Imagine you're setting up a new restaurant. Just like you need to stock the kitchen with initial ingredients before opening day, database seeding provides the initial data your application needs to function properly. Here are some common uses:
Like a test kitchen where chefs practice new recipes, developers need realistic data to test features.
Similar to quality control testing ingredients before using them in dishes, seed data lets you consistently test application features.
Just as restaurants might prepare sample dishes for food critics, seed data creates realistic demonstrations for stakeholders.
Watch out for these common seeding mistakes:
Try these additional challenges to deepen your understanding:
When creating seed data, remember to: