Sequelize не записывает данные так, как ожидалось

#javascript #typescript #postgresql #sequelize.js #next.js

#javascript #typescript #postgresql #sequelize.js #next.js

Вопрос:

В Next.js контекст, я пытаюсь вставить данные в таблицу, используя этот фрагмент кода :

 const user = new User();
user.firstname = "John";
user.lastname = "Appleseed";
user.email = "john.appleseed@apple.com";
await user.create()
  

Но когда я просматриваю журнал, вот что я вижу Войдите из create User

По сути, данные, которые я помещаю в запрос, не записываются в БД, но определенным образом Sequelize получает их (как показано в _previousData ). Но я не знаю, почему они перешли от dataValues к тезисам _previousData

Вот модель, которую я использую

Базовая модель :

 export default class User {

    id!: bigint
    hash!: string
    firstname?: string
    lastname?: string
    email?: string
    isValidated?: boolean = false
   
    async create(): Promise<void> {

        try {

            await UserEntity.create({
                accountValidated: false,
                firstname: this.firstname,
                lastname: this.lastname,
                email: this.email
            });

        } catch (error) {
            console.error('User.create', error.message)
            throw error
        }
    }

}
  

Вот сущность, связанная с Sequelize и моим PG

 

interface UserAttributes {
    id?: bigint
    hash?: string
    firstname?: string
    lastname?: string
    email?: string
    accountValidated: boolean
}

interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}

export default class UserEntity extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes {

    public id!: bigint
    public hash!: string
    public firstname?: string
    public lastname?: string
    public email?: string
    public accountValidated!: boolean
    public readonly createdAt!: Date
    public readonly updatedAt!: Date

    public readonly accounts?: AccountEntity[]; // Note this is optional since it's only populated when explicitly requested in code

    public static associations: {
        accounts: Association<UserEntity, AccountEntity>;
    };

}

UserEntity.init({
    id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true,
        unique: true
    },
    hash: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    },
    firstname: {
        type: DataTypes.STRING,
        allowNull: true
    },
    lastname: {
        type: DataTypes.STRING,
        allowNull: true
    },
    email: {
        type: DataTypes.STRING,
        allowNull: true,
        unique: true,
        validate: {
            isEmail: {
                msg: "This email is malformed"
            }
        }
    },
    accountValidated: {
        type: DataTypes.BOOLEAN,
        defaultValue: false
    },

}, {
    sequelize, // We need to pass the connection instance
    modelName: 'User',
    underscored: true,
    tableName: 'blk_user',
    timestamps: true
})

UserEntity.beforeValidate(user => {
    user.hash = `usr_${v4()}`
})

UserEntity.beforeCreate(instance => console.log('beforeCreate', instance))

  

Что я пробовал

  • [x] Перехваты комментариев
  • [x] Ассоциации комментариев

РЕДАКТИРОВАТЬ 11/16 6:39 CET

Кажется, что это связано с моим способом объявления интерфейсов и моделей моих моделей TS. Я углублюсь в это

Комментарии:

1. Вы смотрели на значение результата из create ?

2. Только что проверил, «createResult»: { «id»: «8», «accountValidated»: false, «firstname»: null, «lastname»: null, «email»: null, «hash»: «usr_3ec34b36-6900-4b10-af30-c6443764fdba», «createdAt»: «2020-11-15T12:28:36.637Z», «updatedAt»: «2020-11-15T12:28:36.637Z» }

3. Проверьте что-то вроде attributes или rawAttributes в UserEntity непосредственно перед create вызовом

4. Не уверен, что вы имеете в виду, поскольку create это статический метод. Я пробовал это: const UserEntity = UserEntity.build({ accountValidated: false, firstname: this.firstname, lastname: this.lastname, email: this.email }) console.log(‘_attributes’, UserEntity . _attributes) console.log(‘_creationAttributes’, идентификатор пользователя. _creationAttributes) Оба являются undefined :'(

5. Я имею в виду посмотреть на статическую модель UserEntity перед вызовом create