Home > front end >  TypeORM unique and default keywords not working for MongoDB in Nestjs
TypeORM unique and default keywords not working for MongoDB in Nestjs

Time:03-11

TypeORM unique and default not working for MongoDB in Nestjs.

My configuration:

core.module.ts

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: () => ({
        type: 'mongodb',
        host: 'localhost',
        port: 27017,
        database: 'blog',
        entities: ['dist/**/*.entity{.ts,.js}'],
        useUnifiedTopology: true,
        synchronize: false,
      }),
    }),
  ],
  exports: [TypeOrmModule],
})

My user entity:

@Entity()
export class User extends BaseEntity {
  @ObjectIdColumn()
  id: ObjectID;

  // not working
  @Column({ unique: true })
  username: string;

  // not working
  @Column({ unique: true })
  email: string;

  @Column()
  displayName: string;

  @Column()
  password: string;

  // not working
  @Column({default:Date.now})
  createdAt?: Date;

  @BeforeInsert()
  async hashPassword() {
    console.log('works');
    this.password = await hash(this.password, 10);
  }
}

My business code:

users.service.ts

 async createUser(credentials: CreateUserDto) {
    try {
      const result = await this.userRepository.create(credentials).save();

      const { username, id, displayName, password } = result;

      const access_token: JwtPayload = {
        user: username,
        id,
        displayName,
        password,
      };
      return {
        token: this.jwtService.sign(access_token, {
          secret: process.env.JWT_SECRET,
        }),
      };
    } catch (error) {
      // no error for unique fields
    }
  }

Also i was try this solutions :

// not working
@Index({ unique: true })
// not working
@Unique(['username'])

Additionally I have a solution for the default value.

@Column()
createdAt?: Date = new Date();

But I don't want to implement it if possible.

I hope i could explain. What can i do for these problems. Is there anyone have an idea?

CodePudding user response:

I was find a solution for unique keyword. I just changed synchronize field value to true value in configuration file. It works now. But still I couldn't find satisfactory solution for default keyword.

CodePudding user response:

For creation and update dates, you can just use respective decorators included with typeorm, and they will be created and updated automatically:

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;

For the unique scenarios, you can try the Unique decorator outside the User class:

@Entity()
@Unique(["username", "email"])
export class User extends BaseEntity { ... }
  • Related