简体   繁体   English

如何在 sequelize Nest.JS 中添加钩子

[英]How to add hooks in sequelize Nest.JS

throw new model_not_initialized_error_1.ModelNotInitializedError(this, Member "${key}" cannot be called. ); throw new model_not_initialized_error_1.ModelNotInitializedError(this, Member "${key}" cannot be called. ); ^ Error: Model not initialized: Member "afterCreate" cannot be called. ^ 错误:模型未初始化:无法调用成员“afterCreate”。 "User" needs to be added to a Sequelize instance. “用户”需要添加到 Sequelize 实例。

@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 .正如我所说的那样,您正在使用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 .您可以在sequelize-typescriptnpm 包页面上阅读更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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