DEV Community

Cover image for Seeding data with Sequelize
Idris Kelani
Idris Kelani

Posted on • Updated on

Seeding data with Sequelize

Just like how we use Git to version control source code, we use migrations and seeders to manage the state of our database schemas.

Sequelize manages the state of the database by saving the name of the migration and seeder(if any) files in the table SequelizeMeta or SequelizeData respectively

We would be looking at the Seeders and how to use them.

When working with Sequelize, you sometimes realize that you need to add static data to the application, e.g, roles, currencies, user types and lots more.

In this tutorial, we would be seeding(adding) the currency of USD and EUR into the Currencies database table of a node js application.

We assume that you already have a node-express-Sequelize project set up. If you haven't, look for tutorials online to do that.

When done with the setup, make sure you have the path to the location of the seeders file in your .sequelizerc file. If it's not there please add it.

const path = require('path');

module.exports = {
  ......
  "seeders-path": path.resolve('./yourdirectory/seeders'),
};
Enter fullscreen mode Exit fullscreen mode

Next is to make sure Sequelize is tracking the seeders file by adding this to the Sequelize config

module.exports = {
    .......
    seederStorage: 'sequelize'
}
Enter fullscreen mode Exit fullscreen mode

The next step is to make sure the Currencies table already exist if it doesn't: create a migration script to add it.

sequelize model:create --name Currency --attributes name:string

Next, Update the Migration file

export default {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Currencies', {
      id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
      },
      name: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: queryInterface => queryInterface.dropTable('Currencies')
};

Enter fullscreen mode Exit fullscreen mode

And the Model file

export default (sequelize, DataTypes) => {
  const Currency = sequelize.define('Currency', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    }
  },
  {
    paranoid: true,
  });
  return Currency;
};

Enter fullscreen mode Exit fullscreen mode

Now We want to add data of USD and EUR to the created Currencies table.

We would create a seed file in the seeders folder by running the command

sequelize seed:generate --name add-currencies

This command generates a seeder file.
The file generated has a name with the current timestamp at the beginning of the file name e.g

20210129170418-add-currency.js.
Enter fullscreen mode Exit fullscreen mode

Sequelize compares the timestamp of the seeders file to determine the order of running the seeder file.

Next, We go-ahead to update the file.

export default {
  up: async (queryInterface) => queryInterface.bulkInsert('Currencies', [
    {
      name: 'USD',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      name: 'EUR',
      createdAt: new Date(),
      updatedAt: new Date()
    },
  ], {}),
  down: async (queryInterface) => {
    await queryInterface.bulkDelete('Currencies', {[Op.or]: [{name: 'USD'}, {name: 'EUR'}]});
  }
};

Enter fullscreen mode Exit fullscreen mode

Now let's take a look at the above code

The up section is the section to add the data into the database table

the queryInterface.bulkInsert adds the data into the Currencies table

The down section: If one decides to remove the data after it has been added, this section will handle that.

Now we have added the script to add seed data

The final step is to run the command or add your start script

sequelize db:seed:all
Enter fullscreen mode Exit fullscreen mode

Now we have successfully seeded the USD and EUR into the Currencies table 🎉🎉🎉🎉🎉🎉🎉🎉

if we decide that we want to remove all the data that has been added in the seeders file, we would run the command

sequelize db:seed:undo:all
Enter fullscreen mode Exit fullscreen mode

or

sequelize db:seed:undo --name 20210129170418-add-currency.js
Enter fullscreen mode Exit fullscreen mode

Visit the Sequelize documentation here

Thanks for reading this 🤗
Enter fullscreen mode Exit fullscreen mode

Idris Kelani 🤗

Top comments (1)

Collapse
 
codewithamitpatil profile image
Amit Shrinivas gujar

sequelize db:seed: undo --name 20210129170418-add-currency.js
this is not working, after checking the documentation found this.

sequelize db:seed:undo --seed 20220824174222-product.js

thanks for explaining things.