NestJS MongoDB验证程序不起作用

时间:2020-08-03 19:08:08

标签: mongodb mongoose nestjs

我尝试在下面的模式中使用验证

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);

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

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

我认为您需要在模型上调用方法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