Typeorm: provide default value for boolean with Mongo database
Asked Answered
M

4

16

I am using typeorm with Mongo database. I want to provide a default value for a column with boolean datatype.

My entity looks as following:

@ObjectIdColumn()
  id: ObjectID;

  @Column()
  name: string;

  @Column()
  startDate: Date;

  @Column()
  endDate: Date;

  @Column()
  inspectionTypeId: string;

  @Column()
  questions: string[];

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

However, when I save into the repo, isActive column is not added.

Malave answered 1/3, 2019 at 10:49 Comment(1)
Official example usage can be seen here, for reference: typeorm.io/#/decorator-reference/columnLevan
H
20

You can do this:

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

if you don't pass a value to isActive it will be true, if you pass a value it will be this value.

Hedonics answered 7/8, 2020 at 21:29 Comment(1)
I'm currently using TypeORM v0.2.29 with a postgres database and this solution worked perfectly for me. I know the original question was about MongoDB but hopefully this helps someone else who stumbles upon this thread.Bluegreen
L
14

I've faced with the same problem in fact. So my stack is the same (MongoDB + TypeORM). I have the same isActive field in the model and what I wanted to do is to set it 'false' by default. I tried to set 'false' and couldn't reach the goal.

I re-read multiple times this part (https://typeorm.io/#/entities)

default: string - Adds database-level column's DEFAULT value.

and got the idea that the default option doesn't work for boolean types at all (maybe I'm wrong).

So in order to set it, I used beforeInsert hook.

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

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

More about hooks: https://typeorm.io/#/listeners-and-subscribers

Lindley answered 24/5, 2019 at 11:51 Comment(2)
That doesn't really set a default value. Doesn't that always set it to false, so if a value did exist it would not be overwritten to falseCamm
You could use this.isActive ??= false instead.Governess
A
1

you just need to write this:

@Column({type:'boolean', default:true})
isActive = true
Apeldoorn answered 29/6, 2023 at 5:41 Comment(0)
M
0

Try this.

@Column({ type: 'boolean', default: true})
Myrta answered 1/3, 2019 at 14:49 Comment(1)
I used it simply as : @Column({ default: true }) myField: boolean; and it worked fine. Moreover, the option indeed exists in TypeORM ColumnOptions : github.com/typeorm/typeorm/blob/…Levan

© 2022 - 2024 — McMap. All rights reserved.