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.
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.
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.
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)
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With