4

I'm trying to create a dynamic schema with fields being required based on the value of another field.

Sample Schema:

const foo = new Schema({
    status: {
        type: String,
        default: "in_process"
    },
    route: {
        type: String,
        default: ""
    },
    code: {
        type: Number,
        default: 0,
        required: function () {
           return this.route === "Results";
        }
    },

});

When I'm doing this, TS notify me with this error:

Property 'route' does not exist on type 'Schema<any> | SchemaTypeOpts<any> | SchemaType'.
  Property 'route' does not exist on type 'Schema<any>'.

How should I properly approach this scenario?

cankentcode
  • 460
  • 1
  • 5
  • 20

1 Answers1

1
interface Ifoo extends Document {
    status:string
    route:string
    code:number
}


const foo = new Schema({
    status: {
        type: String,
        default: "in_process"
    },
    route: {
        type: String,
        default: ""
    },
    code: {
            type: Number,
            default: 0,
            required: function (this:Ifoo) {
               return this.route === "Results";
            }
        },

});
    
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39