Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

594
Views
Mongoose schema validation - this keyword is not working inside validate

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?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!