I'm currently learing TS, and I re-write my old NodeJS/Express project. I need to reference another document's field in the validator, but I recieve an error:
Property 'price' does not exist on type '{ validator: (val: number) => boolean; }'.ts(2339).
Here's the code:
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'
}
});
As you can see I need priceDiscount validator, but I can't reference another field in the document, because TS doesn't know if this field exists. How can I make it to know, that I want to reference another field on the same document?
I do not know the specifics of how mongoose works, but if that code is correct, the issue is that the validator function has its this
bound to something other than the default.
You can annotate the function explicitly to tell TS the type of this
, e.g.
validator: function(this: { price: number }, val: number): boolean {
return val < this.price
},