嘿,我想创建一个独特的电子邮件用户。我使用class-validator进行额外的验证。我在这里找到了很多这样做独特性的建议:
@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自动验证唯一性的解决方案呢?
发布于 2021-01-14 00:04:57
您可以集成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
添加到您希望唯一的属性中
https://stackoverflow.com/questions/65625369
复制相似问题