How to filter Sequelize query by enum values

Viewed 38

I am trying to do something like below:

  # job_type: is of type Array of Enum

  const profiles = await Profile.findAll({
    where: {
      job_type: { [Op.in]: ['Contract', 'Permanent'] },
    },
  });

The above produces an error below

values.map is not a function

The above error kinda makes sense seeing as job_type is an array of enum.

job_type: DataTypes.ARRAY(
   DataTypes.ENUM({
     values: ['Contract', 'Temp', 'Volunteer', 'Permanent'],
   })
),

Stack trace

Trace: TypeError: values.map is not a function
    at ARRAY._value (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/postgres/data-types.js:379:19)
    at ARRAY._stringify (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/postgres/data-types.js:393:29)
    at ARRAY.stringify (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/data-types.js:22:19)
    at PostgresQueryGenerator.escape (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/abstract/query-generator.js:702:30)
    at /Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1908:71
    at Array.map (<anonymous>)
    at PostgresQueryGenerator._whereParseSingleValueObject (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1908:52)
    at PostgresQueryGenerator.whereItemQuery (/Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1728:21)
    at /Users/########/Desktop/####-backend/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1649:25
    at Array.forEach (<anonymous>)

If anyone comes across a process to filter by enum values, I will appreciate any input.

1 Answers

Got a solution to the problem, looking closely at how postgres manages enum and running raw SQL I was able to get the desired result with:

const result = await sequelize.query(
  `SELECT * FROM "Profiles" WHERE array['Contract','Permanent']::"enum_Profiles_job_type"[] @> "job_type"`
);

Without using raw query I was able to solve it with:

const profiles = await Profile.findAll({
  where: {
    job_type: { [Op.contains]: ['Temp','Permanent'] }
  },
});
return profiles;

Op.contains referenced from sequelize-postgres-only-range-operators

Related