【问题标题】:NestJS MongoDB unique fields doesn't workNestJS MongoDB 唯一字段不起作用
【发布时间】:2021-04-13 22:43:10
【问题描述】:

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

@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;
}

但是我给我一个错误:

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

...我认为总体而言这在 NestJS 中是不可能的。

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

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

...这可行,但我得到了完全不同的错误结构,我无法设置自定义错误。

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

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

【问题讨论】:

    标签: mongodb mongoose unique nestjs class-validator


    【解决方案1】:

    你可以集成mongoose-unique-validator插件,它可以自定义错误信息,实现它:

    npm i mongoose-unique-validator
    

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

        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;
        },
      },
    ]),
    

    最后(就像你已经做过的那样)将unique: true 添加到你想要独一无二的属性中

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2023-03-07
      • 2020-11-23
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多