NestJS MongoDB 独特字段不起作用

Pet*_*cht 9 unique mongoose mongodb class-validator nestjs

嘿,我想创建一个具有唯一电子邮件的用户。我正在使用类验证器进行额外验证。我在这里找到了很多建议来实现这样的独特性:

@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;
}
Run Code Online (Sandbox Code Playgroud)

但我抛出了一个错误:

Type 'UserDocument | null' is not assignable to type 'UserInput | null'.
Run Code Online (Sandbox Code Playgroud)

...我认为总的来说,这在 NestJS 中是不可能的。

我还通过添加唯一的道具找到了解决方案:

    @Prop({
        unique: true,
    })
    email!: string;
Run Code Online (Sandbox Code Playgroud)

...这有效,但随后我得到了完全不同的错误结构,并且我无法设置自定义错误。

我在 git 上看到的任何可行的解决方案都是测试服务中的唯一性并抛出错误。

为什么NestJS没有解决方案自动验证唯一性如预期?

You*_*uba 3

您可以集成该mongoose-unique-validator插件,它具有自定义错误消息的能力,以实现它:

npm i mongoose-unique-validator
Run Code Online (Sandbox Code Playgroud)

然后将其应用到您的用户架构:

    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;
    },
  },
]),
Run Code Online (Sandbox Code Playgroud)

最后(正如您已经所做的那样)添加unique: true到您想要独特的属性