12

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.