Sequelize.js 默认getter不返回值,除非在Sequelize中使用TypeScript时使用了`getDataValue()`

Sequelize.js 默认getter不返回值,除非在Sequelize中使用TypeScript时使用了`getDataValue()`,sequelize.js,Sequelize.js,使用Model.Create时,我没有从模型上的getter获取值。但是,如果使用Model.getDataValue() 例子: 我从文档和示例中了解到,这应该返回值 使用TypeScript v4.0.3和Sequelize v6.3.5 模型定义: 导出接口用户属性{ id:字符串; 名字:字符串; createdAt?:日期; 更新日期:日期; } 导出接口UserCreationAttributes扩展可选{ } 导出类用户扩展模型实现用户属性{ 公共id:string; public

使用
Model.Create
时,我没有从模型上的getter获取值。但是,如果使用
Model.getDataValue()

例子: 我从文档和示例中了解到,这应该返回值

使用TypeScript v4.0.3和Sequelize v6.3.5

模型定义:
导出接口用户属性{
id:字符串;
名字:字符串;
createdAt?:日期;
更新日期:日期;
}
导出接口UserCreationAttributes扩展可选{
}
导出类用户扩展模型实现用户属性{
公共id:string;
public firstname:string;
//时间戳!
public readonly createdAt!:日期;
公共只读更新日期!:日期;
}
User.init(
{
身份证:{
类型:DataTypes.UUIDV4,
primaryKey:没错,
},
名字:{
类型:DataTypes.STRING(36),
阿洛诺:是的
},
创建数据:{
类型:DataTypes.DATE,
allowNull:错,
defaultValue:DataTypes.NOW,
},
更新日期:{
类型:DataTypes.DATE,
allowNull:错,
defaultValue:DataTypes.NOW,
}
},
{
续集,
}
);

create
返回Sequelize模型实例,该实例具有元数据,并且记录数据位于元数据中的嵌套对象中。(请尝试
console.log(已创建)
查看记录如何存储在Sequelize实例中)

要获取原始记录数据,您需要
toJSON()


对于未来的读者:这是巴别塔的一个问题。看

在类上创建构造函数,如下所示:

export class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes {
    public id: string;
    public firstname: string;
    ...

    constructor(values: any = {}, options: object = {}) {
        super(values, options)

        this.id = values.id
        this.firstname = values.firstname
        ...
    }
}
并从构造函数中调用:

  constructor(...args) {
    super(...args);

    // hydrate the getters
    restoreSequelizeAttributesOnClass(new.target, this); 
  }

谢谢你的回复,Emma,但是默认的getters应该做你上面描述的事情,并使这些属性水合-因此我的问题。我明白你的意思。我无法复制你的问题。我从
console.info(created.id,created.firstname)获得了正确的值。不过我没有使用TS。是的,这是一个与TS相关的问题
const user = created.toJSON();
console.info(user.id, user.firstname)
export class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes {
    public id: string;
    public firstname: string;
    ...

    constructor(values: any = {}, options: object = {}) {
        super(values, options)

        this.id = values.id
        this.firstname = values.firstname
        ...
    }
}
export default function restoreSequelizeAttributesOnClass(newTarget, self: Model): void {
  Object.keys(newTarget.rawAttributes).forEach((propertyKey: keyof Model) => {
    Object.defineProperty(self, propertyKey, {
      get() {
        return self.getDataValue(propertyKey);
      },
      set(value) {
        self.setDataValue(propertyKey, value);
      },
    });
  });
}

  constructor(...args) {
    super(...args);

    // hydrate the getters
    restoreSequelizeAttributesOnClass(new.target, this); 
  }