Peter Schuhknecht
Peter Schuhknecht

Reputation: 247

NestJS MongoDB unique fields doesn't work

Hey i want do create a user with a unique email. I am using class-validator for additional validation. I found a lot of recommendations here to do uniqueness like that:

@Schema()
export class User {
    @Prop()
    firstName!: string;

    @Prop()
    lastName!: string;

    @Prop()
    email!: {
        type: String,
        required: true,
        index: true,
        unique: true
    };

    @Prop({ nullable: true })
    password?: string;
}

But i throw me an error of:

Type 'UserDocument | null' is not assignable to type 'UserInput | null'.

...and i think overall this is not possible in NestJS.

I also found a solution by adding unique to the props:

    @Prop({
        unique: true,
    })
    email!: string;

... which works, but then i get a completely different structure of errors and i am not able to set custom errors.

Any working solution i saw on git, was testing the uniqueness in the Service and throw an Error.

Why there is no solution for NestJS automatically validating the uniqueness as expected?

Upvotes: 12

Views: 6478

Answers (1)

Ayoub Touba
Ayoub Touba

Reputation: 3007

You can integrate the mongoose-unique-validator plugin, it has the ability to custom the error message, to implement it:

npm i mongoose-unique-validator

then apply it to your User schema:

    MongooseModule.forFeatureAsync([
  {
    name: User.name,
    useFactory: () => {
      const schema = UserSchema;
      schema.plugin(require('mongoose-unique-validator'), { message: 'your custom message' }); // or you can integrate it without the options   schema.plugin(require('mongoose-unique-validator')
      return schema;
    },
  },
]),

and finally (as you already did ) add unique: true to the property you want to be unique

Upvotes: 4

Related Questions