Sequelize Seeders
Introduction
In Sequelize (a popular Node.js ORM for SQL databases), seeders are used to populate your database with initial or dummy data. Seeders are useful during development or testing phases when you need to have a pre-defined set of data in your database. They allow you to automate the process of inserting data into tables, instead of doing it manually.
Seeders are especially useful for initializing your database with required data, such as default user roles, configuration settings, or initial demo data for testing.Creating Seeders
You create a new seeder using the Sequelize CLI command
npx sequelize-cli seed:generate --name demo-userThis will generate a file inside the
seedersfolder, typically located in./seeders/(or wherever you've configured them). The file will look something like this,'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { // Code to insert data into the database }, down: async (queryInterface, Sequelize) => { // Code to undo the changes made by the seeder } };up - This method is used to insert data into the database.
down - This method is used to remove the data added by the seeder, allowing you to reverse the seeding process.
Inserting Data with Seeders
Inside the
upmethod, you can use Sequelize’sbulkInsertmethod to insert data. For example, to insert user data'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.bulkInsert('Users', [ { username: 'JohnDoe', email: 'johndoe@example.com', createdAt: new Date(), updatedAt: new Date() }, { username: 'JaneDoe', email: 'janedoe@example.com', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: async (queryInterface, Sequelize) => { await queryInterface.bulkDelete('Users', null, {}); } };The
bulkInsertmethod inserts two user records into theUserstable.The
bulkDeletemethod removes the inserted records when rolling back.Running Seeders
To run all the seeders, use
npx sequelize-cli db:seed:allThis command executes all the seeders you've defined in the
./seeders/directory.If you want to run a specific seeder,
npx sequelize-cli db:seed --seed <seeder-filename>Undoing Seeders
If you want to undo the seed data (remove it from the database), you can either undo the last seeder,
bashCopy codenpx sequelize-cli db:seed:undoOr undo all the seeders,
bashCopy codenpx sequelize-cli db:seed:undo:allBest Practices
Timestamps - Always provide
createdAtandupdatedAtfields if you’re using Sequelize's default timestamp columns.Unique Constraints - Be cautious about seeding data that may violate unique constraints in your tables, like unique email addresses for users.