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
Sequelize V6 Accessing model name: model.name . Accessing model table name: model. tableName .
Open model files and define the table name as shown below. { sequelize, //define table name tableName: 'users', modelName: 'User', }); { sequelize, //define table name tableName: 'posts', modelName: 'Post', }); To implement the models into the database, we need to run the Node.
Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With