Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

595
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda