乐闻世界logo
搜索文章和话题

How to provide default value for boolean with Mongo database in Typeorm

1个答案

1

When using TypeORM for MongoDB development, setting default values is a common requirement, especially for boolean fields. To set a default value for a boolean field in the entity schema, we can utilize the default property of the @Column decorator within the entity definition.

Here is a specific example:

typescript
import { Entity, ObjectID, ObjectIdColumn, Column } from "typeorm"; @Entity() export class User { @ObjectIdColumn() id: ObjectID; @Column() name: string; @Column({ default: true }) isActive: boolean; }

In this example, we define a User entity containing an isActive field, which indicates whether the user is active. By applying @Column({ default: true }), we set the default value of isActive to true. This ensures that when a new User entity is created and saved to the database without an explicit value for isActive, it is automatically initialized to true.

This approach effectively supports data integrity and simplifies code logic, particularly when managing numerous data entities that require default state indicators.

To validate this functionality, we can create a new user without explicitly setting the isActive field and confirm that the database stores the value as true.

typescript
import { createConnection, getRepository } from "typeorm"; import { User } from "./User"; async function createUser() { const connection = await createConnection(); const userRepository = getRepository(User); const user = new User(); user.name = "John Doe"; await userRepository.save(user); console.log("User has been saved with default isActive value."); } createUser();

By implementing this method, our application can automatically handle the default state of isActive during user data processing, minimizing manual configuration and resulting in more concise and robust code.

2024年8月3日 16:36 回复

你的答案