I am trying to validate the gamesPlayed field of PlayerSchema based on the value of gamesWon and vice versa. The value of gamesPlayed should always be greater than or equals to value of gamesWon.
Here is the piece of code which I'm using for validation
validate: {
validator: (value) => {
return value >= this.gamesWon;
},
message: (props) => `gamesPlayed can't be less than gamesWon, invalid value: ${props.value}`
}
While doing so no matter what I pass in request body, I'm getting the above validation error. After doing some work around, I got to know that I'm getting empty object as the value of this.
So I tried a different approach for validating gamesWon field.
PlayerSchema.path('gamesWon').validate((value)=>{
return value <= this.gamesPlayed;
})
After doing so I'm still getting the empty object as value of this.
Here is the code of my models.js file
const mongoose = require('mongoose');
const PlayerSchema = new mongoose.Schema({
_id: Number,
name: {
type: String,
required: true,
},
gamesWon : {
type: Number,
min: 0,
required: true,
},
gamesPlayed : {
type: Number,
min: 0,
required: true,
validate: {
validator: (value) => {
return value >= this.gamesWon;
},
message: (props) => `gamesPlayed can't be less than gamesWon, invalid value: ${props.value}`
}
},
})
PlayerSchema.path('gamesWon').validate((value)=>{
return value <= this.gamesPlayed;
})
const Player = mongoose.model("Player",PlayerSchema);
module.exports = Player
I'm passing below json as the request body through postman for POST endpoint
{
"_id": 1,
"name": "ClassHacker",
"gamesWon": 5,
"gamesPlayed": 7
}
As far as I know we can use this inside validate, but in my case I don't think its working at all or may be I'm doing something wrong and if that's the case, please let me know what am I doing wrong and how should I validate these fields?