Typeorm

TypeORM 是一个ORM (opens new window)框架

Typeorm 实体 Entity

Typeorm BeforeInsert, BeforeUpdate

  @BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    this.password = await bcrypt.hash(this.password, 12);
  }

直接Save,并不会触发BeforeInsert和BeforeUpdate

async create(attributes: DeepPartial<T>) {
    return this.repository.save(attributes); // 不会触发BeforeInsert
}

解决办法
方法一、利用plainToClass

async create(attributes: DeepPartial<T>) {
    const entity = plainToClass(Admin, attributes);
    return this.repository.save(entity);
}

方法二、利用new Entiry()

async create(attributes: DeepPartial<T>) {
    const entiry = Object.assign(new Admin(), attributes)
    return this.repository.save(entiry);
}

方法三、利用Entity.create(EntitySchema)

async create(dataDto: DataDto) {
    const entityDto = this.respository.create(dataDto)
    return this.repository.save(entityDto);
}
posted @ 2021-12-19 15:54  boygdm  阅读(244)  评论(0编辑  收藏  举报