Home > other >  Is there any way to get the list of validators used in moongoose schema?
Is there any way to get the list of validators used in moongoose schema?

Time:07-01

I want to get the list of validators that is used in a moongoose schema? Something like

const userModel = {
 firstName: {
 type:String,
 required: true
 }
}

// is there any method to get validations like

console.log(userModel.getValidators())

Output:

{
  firstName: {required: true ....etc},
}

CodePudding user response:

Once you setup your model using the SchemaFactory.createForClass method from a class with a @Schema decorator as shown in the docs, you can export the schema. If you then, import the schema and access its obj property, you can extract information about the field.

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

export type CatDocument = Cat & Document;

@Schema()
export class Cat {
  @Prop({ required: true })
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);
import { CatSchema } from './cat.schema';

console.log(CatSchema.obj.name.required);  // true
console.log(CatSchema.obj.age.type.name);  // 'Number'
  • Related