typescript - 使用 TypeScript 在 mongoose.Schema 中的 `required` 字段中使用函数

标签 typescript mongoose mongoose-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";
        }
    },

});

当我这样做时,TS 通知我这个错误:
Property 'route' does not exist on type 'Schema<any> | SchemaTypeOpts<any> | SchemaType'.
  Property 'route' does not exist on type 'Schema<any>'.

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

最佳答案

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

});
    

关于typescript - 使用 TypeScript 在 mongoose.Schema 中的 `required` 字段中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209292/

相关文章:

angular - 如何以 Angular 4 发射事件发射器?

javascript - Mongoose 填充虚拟而不是整个架构

node.js - 跳过 Mongoose 中某些更新的时间戳中间件

node.js - 更新用户信息 mongoose, MongoDB, NodeJS

node.js - 我可以获得快速错误处理程序来捕获 Mongoose 回调中抛出的异常吗?

javascript - 我的 .find 函数没有调用我的数据库

javascript - 如何在侧面嵌套数组 Mongoose 中定义对象数组

javascript - 在输入字段中的文本输入后添加单位 Angular 5

javascript - Typescript:将对象属性标记为不可枚举?

javascript - 跨多个文件的 Typescript 内部模块与 js 缩小