【问题标题】:NestJS MongoDB validators not worksNestJS MongoDB 验证器不起作用
【发布时间】:2020-11-23 21:04:38
【问题描述】:

我尝试在下面的架构中使用验证

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema({
  validateBeforeSave: true,
})
export class User extends Document {
  @Prop({
    unique: [true, 'login field must be unique'],
    required: [true, 'login field must be defined'],
  })
  login: string;

  @Prop({
    required: [true,'password required'],
    minlength: 4,
  })
  password: string;

  @Prop({
    type: Date,
  })
  createdAt: Date;

export const UserSchema = SchemaFactory.createForClass(User);

但是当我保存一个没有密码的新用户时,什么也没发生。

可能是什么问题?

【问题讨论】:

    标签: mongodb mongoose nestjs


    【解决方案1】:

    我认为您需要在模型上调用方法validate,例如:

    const User = db.model('User', userSchema);
    const user = new User();
    
    user.email = 'test@test.co';
    user.name = 'test';
    user.validate().catch(error => {
      assert.ok(error);
    });
    

    检查文档Mongoose Validation,即使他们说它适用于save 方法,我也会在100% 确定之前调用validate,他们会检查它。

    【讨论】:

    • 我现在不知道如何使用 Nestjs 做到这一点。此外我在装饰器中设置了validateBeforeSave: true,
    • 保存前不能调用这个方法吗?
    • 这不是针对nestjs @cojack的答案
    • @MohamedImran 没有在这个框架上进行验证的特定 Nestjs 方法。
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2020-01-25
    • 2022-01-17
    • 2021-04-13
    • 2022-08-02
    相关资源
    最近更新 更多