简体   繁体   中英

How to add hooks in sequelize Nest.JS

throw new model_not_initialized_error_1.ModelNotInitializedError(this, Member "${key}" cannot be called. ); ^ Error: Model not initialized: Member "afterCreate" cannot be called. "User" needs to be added to a Sequelize instance.

@Table({
  tableName: 'users',
})
export class User extends Model<User> {
@Column({
    type: DataType.STRING,
    allowNull: false,
  })
  first_name: string;
....
}
User.afterCreate(async (user, options) => {
  console.log('New User created:');
  console.log(user.first_name);
  console.log(user.email);
});

As I got it right, you're using sequelize-typescript . If yes, then you need to use another approach to define hooks.

import { AfterCreate, Table, Model } from 'sequelize-typescript';

@Table
export default class User extends Model {
  // ... definition of your columns and other model-related stuff

  @AfterCreate
  static methodName(instance: User) {
    // do something
  }
}

You can read more on the sequelize-typescript 's npm package page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM