Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda