键入Mongoose验证函数

qxsslcnc  于 2023-01-13  发布在  Go
关注(0)|答案(2)|浏览(94)

我正在帮助一个使用MongoDB来持久化数据的 typescript 应用程序。我们正在尝试做的事情之一是摆脱any的使用。
下面的代码用于定义mongoose模式的一部分:

priceMax: {
  max: 10000000,
  min: 0,
  required: function (this: FeePricing & Document) {
    return this.priceMin === undefined;
  },
  type: Number,
  validate: [
    {
      message: 'Max price cannot be lower than min price',
      validator: function (v: number) {
        if ((this as any).priceMax === null || (this as any).priceMax === undefined) return true;
        return (this as any).priceMin ? v >= (this as any).priceMin : v >= 0;
      },
    },
    {
      message: 'Max price cannot be higher than 50000 for this feeType',
      validator: function (v: number) {
        return !(!feeTypesWithoutMaxLimit.includes((this as any).feeType) && v > 50000);
      },
    },
  ],
},
priceMin: {
  max: 10000000,
  min: 0,
  required: function () {
    return (this as any).priceMax === undefined;
  },
  type: Number,
  validate: {
    message: 'priceMin cannot be higher than priceMax',
    validator: function (v: number) {
      return (this as any).priceMax ? v <= (this as any).priceMax : v >= 0;
    },
  },
},
updatedAt: { type: Date },
updatedBy: { type: String },

我大概知道函数在做什么,但是这里的类型让我很困惑。
我怎么才能摆脱this as any?为什么不只是使用FeePricing的类型-例如(this as FeePricing)FeePricing似乎是只是另一个类型从我的应用程序[,其中priceMinpriceMax]与Document接口相结合。ReactJS的Document在这里有什么帮助?为什么需要它?validate中的this是否为上面定义的类型FeePricing & Document
谢谢

qojgxg4l

qojgxg4l1#

this是验证配置的上下文。由于TypeScript无法推断其类型(因为它可以更改为任何类型),我建议您创建自己的自定义类型,如FeePricing。我不太确定您当前的FeePricing包含哪些属性,因为它没有包含在示例中,但我会将其设置为如下:

interface FeePricing {
  priceMin?: mongoose.Schema.Types.Number | null,
  priceMax?: mongoose.Schema.Types.Number | null,
  feeType?: mongoose.Schema.Types.Number | null,
}

然后,您可以像这样使用它:

(this as FeePricing).priceMax

为什么属性是可选的,也是null,因为我可以看到你的一些逻辑检查他们是undefined还是null,因此这些类型将反映他们可能不存在于运行时,并帮助您正确验证。此外,如果FeePricing类型用于其他东西,你当然可以改变这个类型名称为其他东西。
要回答您关于ReactJs Document的问题,它没有添加任何帮助来推断mongoose配置类型,并且确实可以删除。

gcuhipw9

gcuhipw92#

据我所知,Mongoose中的模式是用来定义存储在MongoDB中的文档的,如果我是正确的,你可以创建一个Feeprising的模型/接口,并将其用作类型。

export interface FeePricing {
  priceMax: number;
  priceMin: number;
}

this是自由定价对象。
希望这能帮上忙

相关问题