8

I know a simple answer could be query table with all attributes returned.

However, since the models are defined in code, I want to know is it possible to get the result without querying database? Or, if query is necessary, which query is the optimised one?

Btw, I am using Sequelize V5 and Mysql 5.7.

lee
  • 111
  • 1
  • 10

3 Answers3

10

You can iterate over rawAttributes of the Model class

for( let key in Model.rawAttributes ){
    console.log('Field Name: ', key); // this is name of the field
    console.log('Field Type: ', Model.rawAttributes[key].type.key); // Sequelize type of field
}

The keys of rawAttributes are the field names aka column names; the values of rawAttributes are the Sequelize definitions of those columns, including properties explained in the init/define methods., such as type, allowNull, defaultValue, unique, etc...

Remember to check rawAttributes after you create any associations and any other setup on your Model (Model.hasOne() or Model.belongsTo(), anything in your Model.associate() function), otherwise the attributes object won't include foreign key columns.

Side-note, in Sequelize v4, Model.attributes===Model.rawAttributes, so they are aliases for the same thing.

In Sequelize v6+, you can use Model.getAttributes(), which is documented

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
  • 1
    Thanks. Is the "rawAttributes" explained in official documents? It will hard to figure it out without documentation. – lee Jan 15 '20 at 00:21
  • yeap, the documentation of sequelize isn´t that good but checking how are the files are generated you can figureout, and with some research – Rabindranath ferreira Feb 25 '20 at 21:10
2

You can also use this as an answer:

for( let key of Object.keys(models.Modelname.attributes))   {
      columns.push({
          name:key,
          type:models.Modelname.attributes[key].type.key
      });
}
  • This would be an expensive operation, re-calculating `Object.keys` in each iteration of the loop. – skmak Aug 02 '23 at 11:04
1

It seems each model has an attribute "rawAttributes" which include all columns name. This may not be the official way, but it can solve my problem.

lee
  • 111
  • 1
  • 10