typeorm: @Unique doesn't work in MongoDB

Issue type:

[ ] question [x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [x] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] sqlite [ ] sqljs [ ] react-native

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

@Entity()
export class PackageSettings implements IPackageSettings {
    @ObjectIdColumn() id: ObjectID;

    @Column({ unique: true })
    @IsString()
    @IsNotEmpty()
    name: string;

    @Column('simple-json') value: object;
}

and

@Entity()
@Unique(['name'])
export class PackageSettings implements IPackageSettings {
    @ObjectIdColumn() id: ObjectID;

    @Column()
    @IsString()
    @IsNotEmpty()
    name: string;

    @Column('simple-json') value: object;
}

No index unique created in mongodb and no error thrown when I try to save multiple objects with same name attribute.

Is decorator @Unique only RDBMS-specific ?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (11 by maintainers)

Most upvoted comments

You need to put synchronize: true in your connection options. This flag executes indices synchronization

@Index({ unique: true }) I checked on the version 0.2.3, it’s works for me

But, it’s very strange that there are 2 syntaxes @Column({ unique: true }) and @Index({ unique: true })

I use mongodb version 3.4.7

Any update regarding this issue?

I tried this :

@Entity()
export class PackageSettings implements IPackageSettings {
    @ObjectIdColumn() id: ObjectID;

    @Column()
    @IsString()
    @IsNotEmpty()
    @Index({ unique: true })
    name: string;

    @Column('simple-json') value: object;
}

It doesn’t work.