Home > Web Front-end > JS Tutorial > Sequelize seeders for static data

Sequelize seeders for static data

Linda Hamilton
Release: 2024-12-29 03:10:10
Original
165 people have browsed it

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;
  };
Copy after login

To create a seeder template:

npx sequelize-cli seed:generate --name add-static-task-types
Copy after login

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
    });
  }
};

Copy after login

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).
Copy after login

To run the seed:

npx sequelize-cli db:seed:all
Copy after login

Success as shown in DBeaver window:

Sequelize seeders for static data

The above is the detailed content of Sequelize seeders for static data. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template