在 Nodejs Sequelize 模型中,如何获取属性的类型信息?

use*_*868 5 javascript postgresql node.js sequelize.js

我有一个带有Postgressequelizein的工作模型NodeJS。假设模型是Person,具有nameage字段。现在我想动态检查模型类并获取有关它的属性的信息,例如它们的名称和最重要的类型

使用Person.attributes 我得到一些信息:

name:
{ type:
  { options: [Object],
    _binary: undefined,
    _length: 255 },
Run Code Online (Sandbox Code Playgroud)

但是正如你所看到的,该type对象并没有告知name它是一个varcharboolean

有谁知道,如何获得这些信息 sequelize

pio*_*ias 8

您可以迭代rawAtributes模型

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
}
Run Code Online (Sandbox Code Playgroud)

所以name作为 a的例子Sequelize.STRING

Field: name
Type: STRING
Run Code Online (Sandbox Code Playgroud)

或者你可以做几乎相同的迭代,但使用Model.rawAttributes[key].type.key你可以使用Model.rawAttributes[key].type.toSql(),这会产生这个结果

Field: name
Type: VARCHAR(255)
Run Code Online (Sandbox Code Playgroud)

编辑

defaultValue字段访问:

Model.rawAttributes[field].defaultValue

检查字段是否允许NULL值:

Model.rawAttributes[field].allowNull