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

176
Vistas
Mongoose model `this` is undefined in its own definition

I am trying to define a conditional required field for a mongoose model in the following way:

const userSchema = new mongoose.Schema({
    email: {
        type: String,
    },
    emailVerified: {
        type: Boolean,
        required: true
    },
    hash: {
        type: String,
        required: function() {
            if(!this.emailVerified) return true
            return false
        }
    },
    oauth: {
        type: Boolean,
        required: true,
    },
    password: {
        type: String,
        required: function() {
            if(this.oauth) return false
            return true
        }
    }

})

export default mongoose.models.Users || mongoose.model('Users', userSchema)

My intention is that I only want the hash field to be required when emailVerified === false, and the password field to be required only when oauth === true.

The thing is that when I try to add a document in the Users collection I get the following error:

Error: Users validation failed: hash: Cannot read property 'emailVerified' of undefined, password: Cannot read property 'oauth' of undefined

By looking at the documentation I understand that I should be able to reference the model in its own definition.

about 4 years ago · Juan Pablo Isaza
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