Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeorm: provide default value for boolean with Mongo database

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.

like image 926
Supriya Narayan Avatar asked Mar 01 '19 10:03

Supriya Narayan


People also ask

What is typeorm MongoDB integration?

While TypeORM is primarily known as an ORM for SQL databases such as PostgreSQL, MySQL etc, it also provides excellent support for NoSQL database such as MongoDB. The great part is that the TypeORM MongoDB Integration uses similar concepts to SQL support.

Does Resty typeorm support MongoDB?

TypeORM has basic MongoDB support, find out more by reading official docs. Resty framework fully supports integration with typeorm without any extra library or adapter. You can find full example in resty starters repository.

What is an example of a query in MongoDB?

Please see Query Documents in the MongoDB manual for examples of queries in the mongo shell, Compass, and drivers. The relevant example for your question is Specify AND Conditions: db.foo.find ( { boolean: true, string: ‘someString’}).limit (20)

What is default value in MongoDB?

Default Value: This value is entered when no value is entered as a value of the field in the collection. Running the server on Local IP: Data is the directory where MongoDB server is present. Output: Console output- Default Value is inserted.


2 Answers

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.

like image 160
Hugo Avatar answered Nov 16 '22 16:11

Hugo


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

like image 35
Roman Sachenko Avatar answered Nov 16 '22 18:11

Roman Sachenko