打字稿:如何在本文档中引用另一个文档的字段?

时间:2021-02-19 12:03:40

标签: javascript node.js typescript mongoose mongoose-schema

我目前正在学习 TS,并且我重写了我的旧 NodeJS/Express 项目。我需要在验证器中引用另一个文档的字段,但收到一个错误:

<块引用>

属性 'price' 不存在于类型 '{validator: (val: number) => boolean; }'.ts(2339).

代码如下:

const tourSchema = new mongoose.Schema({
  price: {
    type: Number,
    required: [true, ' A tour must have a price']
  },
  priceDiscount: {
    validator: function(val: number): boolean {
      return val < this.price
    },
    message: 'Discount price ({VALUE}) should be below regular price'
  }
});

Here's the error

如您所见,我需要 priceDiscount 验证器,但我无法引用文档中的另一个字段,因为 TS 不知道该字段是否存在。我怎样才能知道我想引用同一个文档中的另一个字段?

2 个答案:

答案 0 :(得分:0)

我不知道 mongoose 如何工作的细节,但如果该代码是正确的,问题是验证器函数的 this 绑定到默认值以外的其他内容。

您可以显式地对函数进行注释以告诉 TS the type of this,例如

validator: function(this: { price: number }, val: number): boolean {
  return val < this.price
},

答案 1 :(得分:0)

另外,我在上面的代码中犯了一个错误。正确的代码,@H.B的解决方案是:

const tourSchema = new mongoose.Schema({
  price: {
    type: Number,
    required: [true, ' A tour must have a price']
  },
  priceDiscount: {
    type: Number,
    validate: {
      validator: function(this: { price: number }, val: number): boolean {
        return val < this.price;
      }
    },
    message: 'Discount price ({VALUE}) should be below regular price'
  }
});
相关问题