f1nn
f1nn

Reputation: 7047

Is there a way to get attributes // associations by previously defined Sequelize Model?

I need to get some data by previously defined Sequelize Model.

What I need:

* attributes list
  * attribute name
  * attribute type (INTEGER, STRING,...)
  * was it generated by association method?
* list of associations
  * association type (belongsTo, hasMany, ...)

For some reason it's rather hard to inspect Sequelize models in console:

> db.sequelize.models.Payment
Payment // <- it's valid Sequelize Model {Object}, however its not inspectable

> db.sequelize.models.Payment.attributes
...
type:
 { type: { values: [Object] },
   values: [ 'cash', 'account', 'transfer' ],
   Model: Payment,
   fieldName: 'type',
   _modelAttribute: true,
   field: 'type' },
sum: 
 { type: 
    { options: [Object],
      _length: undefined,
      _zerofill: undefined,
      _decimals: undefined,
      _precision: undefined,
      _scale: undefined,
      _unsigned: undefined },
   Model: Payment,
   fieldName: 'sum',
   _modelAttribute: true,
   field: 'sum' },
 ...

As you see, there is no actual info about fields types. The same happens with associations.

So, is there any reliable "official" way to extract this data from Model class without digging and reversing object?

Upvotes: 25

Views: 25216

Answers (2)

Dale Ryan
Dale Ryan

Reputation: 843

Sequelize v6

rawAttributes() method is now deprecated, use getAttributes() method instead. Documentation

Example usage:

import models from "./src/models/index.js"
import User from "./src/models/User.js"

console.log(models.sequelize.model('user').getAttributes())
console.log(User.getAttributes())

Upvotes: 8

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

Try Payment.rawAttributes, which is an object with property name as key, and an object with property details. property.type.key is a string with the type.

Payment.associations is an object of associations - the key is the name, and each association will have an associationType property - you can also do association instanceof sequelize.Association.BelongsTo etc.

Upvotes: 57

Related Questions