Sequelize Seeding ARRAY(ENUM)
Asked Answered
M

1

9

I cannot seem to figure out how to seed ARRAY(ENUM) using Sequelize. When I am registering a user via my app, I can create a new user fine, but when I am using the queryInterface.bulkInsert in a seed file, I am getting:

ERROR: column "roles" is of type "enum_Users_roles"[] but expression is of type text[]

here is my code:

return queryInterface.bulkInsert('Users', [
          {
              email: faker.internet.email(),
              roles: ['user'],
              password: "hash",
              public_id: faker.random.uuid(),
              created_at: new Date(),
              updated_at: new Date()
          }
      ]);

and here is my migration file for the user:

return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      email: {
        type: Sequelize.STRING,
          allowNull: false
      },
      password: {
        type: Sequelize.STRING,
          allowNull: false
      },
      roles: {
        type: Sequelize.ARRAY(Sequelize.ENUM({
            values: ['user', 'setter', 'admin']
        })),
          allowNull: false
      },
      public_id: {
        type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4,
          allowNull: false
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE
      }
    })

I am just assuming that I am doing it wrong, but I cannot find any documentation on how to do it correctly. If anyone can help and explain (teach a man to fish), I would appreciate it.

Margaret answered 10/10, 2019 at 15:13 Comment(0)
M
4

Someone answered on github here

This is their answer which worked for me (and I greatly appreciate)

You can use this code

class Item extends Sequelize.Model { }

Item.init({
  name: { type: DataTypes.STRING },
  values: {
    type: DataTypes.ARRAY(DataTypes.ENUM({
      values: ['a', 'b']
    }))
  }
}, {
  sequelize,
  timestamps: true
})

sequelize.sync({ force: true }).then(async () => {
  await sequelize.queryInterface.bulkInsert('Items', [
    {
      name: 'xyz',
      values: sequelize.literal(`ARRAY['a']::"enum_Items_values"[]`),
      createdAt: new Date(),
      updatedAt: new Date()
    }
  ]);
});
Executing (default): INSERT INTO "Items" ("name","values","createdAt","updatedAt") VAL


  [1]: https://github.com/sequelize/sequelize/issues/11541#issuecomment-542791562

Obviously you'll want to change the array values and enum values. For example, mine would be ARRAY['user']::"enum_Users_values"[]

Margaret answered 16/10, 2019 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.