lee
lee

Reputation: 131

Sequelize - How to list/view all columns of existing model

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.

Upvotes: 10

Views: 11046

Answers (3)

Rabindranath ferreira
Rabindranath ferreira

Reputation: 112

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

Upvotes: 10

Pulin Jhaveri
Pulin Jhaveri

Reputation: 45

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

Upvotes: 2

lee
lee

Reputation: 131

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.

Upvotes: 1

Related Questions