Typeorm:为Mongo数据库提供boolean的默认值

问题描述 投票:1回答:2

我正在使用带有Mongo数据库的typeorm。我想为boolean数据类型的列提供默认值。

我的实体看起来如下:

@ObjectIdColumn()
  id: ObjectID;

  @Column()
  name: string;

  @Column()
  startDate: Date;

  @Column()
  endDate: Date;

  @Column()
  inspectionTypeId: string;

  @Column()
  questions: string[];

  @Column('boolean', {default: true})
  isActive: boolean;

但是,当我保存到回购时,没有添加isActive列。

mongodb boolean default-value typeorm
2个回答
0
投票

事实上我遇到了同样的问题。所以我的堆栈是相同的(MongoDB + TypeORM)。我在模型中有相同的isActive字段,我想要做的是默认设置为'false'。我试图设置'假'而无法达到目标。

我重读了这部分(https://typeorm.io/#/entities

default:string - 添加数据库级列的DEFAULT值。

并且认为default选项根本不适用于布尔类型(也许我错了)。

所以为了设置它,我使用了beforeInsert钩子。

  @Column({
    nullable: false,
    select: false,
  })
  isActive: boolean;

  @BeforeInsert()
  beforeInsertActions() {
    this.isActive = false;
  }

更多关于钩子:https://typeorm.io/#/listeners-and-subscribers


-2
投票

试试这个。

@Column({ type: 'boolean', default: true})
© www.soinside.com 2019 - 2024. All rights reserved.