Home > Net >  Sequelize: How to select subset of an array column?
Sequelize: How to select subset of an array column?

Time:08-03

I have a table with an array column called tokens

I can query it via npm sequelize with no issues, Sometimes this column may have upto 20k elements in the array which i dont always need. I need just 10 elements from it

In SQL this would be

select tokens[:10] from schema.table 

How I do this using sequelize ?

This is what I'm doing now

const whereClause = {
        where: { active: true },
        attributes: {
          exclude: ['tokens'],
          include: ['tokens[:10]'],
        },
      };

table.findAll(whereClause);

This gives the following error

original: error: column "tokens[:10]" does not exist

It is looking for a column named "tokens[:10]" instead of taking a subset. What am I doing wrong ?

CodePudding user response:

You can use literals when you select attributes in sequelize. You can try something like this,

    const whereClause = {
        where: { active: true },
        attributes: [
           [Sequelize.literal(`tokens[:${sub-array-length}]`), 'tokens']
        ]
      };

    table.findAll(whereClause);

Note the use of colons to denote the sub-array slicing index

  • Related