user3139868
user3139868

Reputation: 403

In a Nodejs Sequelize model, how to obtain type information of attributes?

I have a working model with Postgres and sequelize in NodeJS. Say the model is Person and has name and age fields. Now I want to dynamically inspect the model class and obtain information about it's attributes, like their name and most of all type.

Using Person.attributes I get some information:

name:
{ type:
  { options: [Object],
    _binary: undefined,
    _length: 255 },

But as you can see the type object does not inform about name being a varchar or boolean.

Does anyone know, how to get this information with sequelize

Upvotes: 6

Views: 8057

Answers (3)

Being Spectator
Being Spectator

Reputation: 41

item.rawAttributes[key].type.key === this.DataTypes.JSONB.key; @piotrbienias Is above comparison valid ? (Sorry for writing here as I can't add comments)

Upvotes: 0

piotrbienias
piotrbienias

Reputation: 7401

You can iterate over rawAtributes of Model

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

So the example for name being a Sequelize.STRING would be

Field: name
Type: STRING

Or you can do almost the same iteration but instead using Model.rawAttributes[key].type.key you can use Model.rawAttributes[key].type.toSql(), which would generate this result

Field: name
Type: VARCHAR(255)

EDIT

Accessing defaultValue of field:

Model.rawAttributes[field].defaultValue

Checking if field allows NULL values:

Model.rawAttributes[field].allowNull

Upvotes: 10

vitaly-t
vitaly-t

Reputation: 25840

You are looking for native type information, it seems.

I'm not familiar with Sequelize, except I know it uses node-postgres driver underneath, which automatically provides the type information with every query that you make.

Below is a simple example of dynamically getting type details for any_table, using pg-promise:

var pgp = require('pg-promise')(/*initialization options*/);
var db = pgp(/*connection details*/);

db.result('SELECT * FROM any_table LIMIT 0', [], a => a.fields)
    .then(fields => {
        // complete details for each column 
    })
    .catch(error => {
        // an error occurred
    });

There are several fields available for each column there, including name and dataTypeID that you are looking for ;)

As an update, following the answer that does use Sequelize for it...

The difference is that here we get direct raw values as they are provided by PostgreSQL, so dataTypeID is raw type Id exactly as PostgreSQL supports it, while TYPE: STRING is an interpreted type as implemented by Sequelize. Also, we are getting the type details dynamically here, versus statically in that Sequelize example.

Upvotes: 1

Related Questions