【问题标题】:Use function in `required` field in mongoose.Schema using TypeScript使用 TypeScript 在 mongoose.Schema 的 `required` 字段中使用函数
【发布时间】:2020-05-29 05:56:37
【问题描述】:

我正在尝试创建一个动态架构,其中需要基于另一个字段的值的字段。

示例架构:

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";
        }
    },

});

当我这样做时,TS 会通知我这个错误:

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

我应该如何正确处理这种情况?

【问题讨论】:

    标签: typescript mongoose mongoose-schema


    【解决方案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";
                }
            },
    
    });
        
    

    【讨论】:

    • 嗨@user16348030,请考虑为您的答案添加一些解释。
    猜你喜欢
    • 2012-01-07
    • 2023-03-24
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多