如何在 NestJs 和 Mongoose 中检查和管道唯一的电子邮件字段
在 Nestjs mongoose 中发送查询之前,我需要验证电子邮件以修复 E11000
错误。
1.控制器
@Post('register')
async register(@Body() register: RegisterDto) {
return this.authService.register(register);
}
2。数据类型
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class RegisterDto {
...
/* I wish to add some code here with Validate() */
/* such as @Validate(UserExistsRule) */
@IsNotEmpty()
@IsEmail()
email: string;
...
}
3. main.ts
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
...
app.useGlobalPipes(new ValidationPipe());
...
}
4.架构
@Prop({ required: true, index: true, unique: true })
email: string;
问题是,当 MongoDB 上已有电子邮件地址时,我必须处理重复错误。
如果您知道如何使用 Nest.Js 管道和 Mongoose 中的独特字段处理自定义验证,您可以写在这里吗?
++++++++++++++++++++++++++++++++++++++++++++
希望我希望在尝试之前添加验证注册一个新文档。不处理以下错误:
ERROR [ExceptionsHandler] E11000 duplicate key error collection: nnm-starter.users index: email_1 dup key: { email: "[email protected]" }
++++++++++++++++++++++++++++++++++++++++++
I need to validate the email to fix the E11000
error before sending a query in nestjs mongoose.
1. Controller
@Post('register')
async register(@Body() register: RegisterDto) {
return this.authService.register(register);
}
2. Data Type
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class RegisterDto {
...
/* I wish to add some code here with Validate() */
/* such as @Validate(UserExistsRule) */
@IsNotEmpty()
@IsEmail()
email: string;
...
}
3. main.ts
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
...
app.useGlobalPipes(new ValidationPipe());
...
}
4. Schema
@Prop({ required: true, index: true, unique: true })
email: string;
The issue is I have to handle duplicate errors when there is an email address already on MongoDB.
If you know how to handle custom validation with unique fields in Nest.Js pipe and Mongoose, Could you write here?
++++++++++++++++++++++++++++++++++++++++
Hopefully, I wish to add validation before trying to register a new Document. Without handling the below error:
ERROR [ExceptionsHandler] E11000 duplicate key error collection: nnm-starter.users index: email_1 dup key: { email: "[email protected]" }
++++++++++++++++++++++++++++++++++++++++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论