【问题标题】:Typescript: How can I reference another document's field inside of this document?打字稿:如何在此文档中引用另一个文档的字段?
【发布时间】:2021-05-22 10:12:02
【问题描述】:

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

类型 '{ 验证器: (val: number) => boolean; 上不存在属性 'price' }'.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 不知道该字段是否存在。我怎样才能知道我想引用同一文档中的另一个字段?

【问题讨论】:

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


【解决方案1】:

我不知道 mongoose 的具体工作原理,但如果该代码是正确的,那么问题是验证器函数的 this 绑定到默认值以外的其他东西。

你可以显式注释函数告诉 TS the type of this,例如

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

【讨论】:

  • 不幸的是,tihs 不起作用,因为验证器函数只接收一个参数。
  • @Craig:这不会被解释为一个额外的论点。它只是向this 添加一个类型。
  • 成功了!我还阅读了文档。我不知道它是这样工作的,谢谢。我只是认为我们将其作为论据传递。谢谢!另外,也许您可​​以告诉我,我想知道为什么这段代码:this: { price: number } 以它的工作方式工作。我知道 TS 接受它并看到“this”必须是一个具有属性 price 的对象,它是一个字符串。但是它不应该期望“this”是一个只有财产价格的对象吗?
  • @Craig:我不太明白你的问题。如果你像这样输入this,它应该只注册为具有price 属性(这是一个number,但是你写了两次字符串?)。
  • 对不起,我打错了,我的意思是数字而不是字符串。我的意思是,我理解语法: this: { price: number } 告诉 TS 对象“this”将有一个属性价格,而这个属性将是一个数字。虽然事实上我们知道,“这个”还有一些其他的属性,而不仅仅是价格。这让我很困惑,因为如果我们创建一个这样的类型:let foo: {price: number},我们会告诉 TS foo 必须是一个只有 price 属性的 obj。我想知道为什么它会这样工作。
【解决方案2】:

另外,我在上面的代码中犯了一个错误。正确的代码,@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'
  }
});

【讨论】:

    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多