I have a problem with validation in mongoose with NEST. According to the code, validation should work, but when I don't check it manually, duplicate e-mails and userId are still saved to the database.
//schema
export type UsersDocument = HydratedDocument<Users>
@Schema()
export class Users extends Document {
@Prop({ required: true, index: true, unique: true })
email: string;
@Prop({ required: true })
password: string;
@Prop({ required: true, index: true, unique: true })
userId: string;
@Prop()
refreshToken?: string | null | undefined;
}
export const UsersSchema = SchemaFactory.createForClass(Users); ```
//usersService
```async createUser(user: UserInterface): Promise<UserInterface> {
const userExists = await this.userModel.findOne({ email: user.email });
const userIdExists = await this.userModel.findOne({ userId: user.userId });
if (userExists || userIdExists) {
//Here i cheking manuallu
}
const newUser = new this.userModel(user);
return newUser.save();
}```
//auth service
``` async register(dto: AuthDto) {
const hashPassword = await this.hashData(dto.password);
const customId = uuidv4();
const newUser = {
email: dto.email,
password: hashPassword,
userId: customId
}
await this.usersService.createUser(newUser);
} ```
//controller
``` @Public()
@Post('/register')
@HttpCode(HttpStatus.CREATED)
register(@Body() dto: AuthDto) {
return this.authService.register(dto)
}```
Yes, the same way you pass UUIDs to the other collections to relate documents to each other or different parts of the application, you can do the same with ObjectIds. The approach is the same.