DEV Community

theBridge2
theBridge2

Posted on

Sequelize seeders for static data

Very brief post on how to do seeders in sequelize. Seeders are how you create static data in a database that you want to be present without the users having to create it.

The goal of this is to add some static data to my very basic task type table in my todo app defined by this model:

module.exports = (sequelize, Sequelize) => {
    const static_task_type = sequelize.define("static_task_type", {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      task_type: {
        type: Sequelize.STRING,
        allowNull: false
      }
    });
    static_task_type.associate = function (models) {

    };

    return static_task_type;
  };
Enter fullscreen mode Exit fullscreen mode

To create a seeder template:

npx sequelize-cli seed:generate --name add-static-task-types
Enter fullscreen mode Exit fullscreen mode

This is filling in the seeder template with a couple of task types.

'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {


  await queryInterface.bulkInsert('static_task_types',[
      { id: 1, task_type: 'Deep' ,createdAt: new Date(),updatedAt: new Date()},
      { id: 2, task_type: 'Shallow' ,createdAt: new Date(),updatedAt: new Date()},
      { id: 3, task_type: 'Phone Call' ,createdAt: new Date(),updatedAt: new Date() },
      { id: 4, task_type: 'Errands' ,createdAt: new Date(),updatedAt: new Date()}]

      ) 
  },



  async down (queryInterface, Sequelize) {
    await queryInterface.bulkDelete('static_task_types', null, {
      truncate: true,
      cascade: true, // Optional: Will also delete dependent rows if foreign keys are used
      restartIdentity: true, // Optional: Resets auto-increment counters
    });
  }
};

Enter fullscreen mode Exit fullscreen mode

NOTE: don't forget to add the createdAt and updatedAt columns, otherwise you will get the following error:

ERROR: null value in column "createdAt" of relation "static_urgencies" violates not-null constraint
ERROR DETAIL: Failing row contains (1, Now, null, null).
Enter fullscreen mode Exit fullscreen mode

To run the seed:

npx sequelize-cli db:seed:all
Enter fullscreen mode Exit fullscreen mode

Success as shown in DBeaver window:

Image description

Top comments (0)