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

174
Visualizações
Mongoose: How to set the value of a field based on another field?

I am trying to have a field in the schema based on another.

I found this solution:

const PostSchema = new Schema({
    title: { type: String, required: true },
    titleUpperCase: { type: String }
    content: { type: String, required: true },
    creation: { type: Date, default: Date.now() }
})
PostSchema.pre('save', (next) => {
    this.titleUpperCase = this.title.toUpperCase()
    next()
})

In the above code, I want the value of the titleUpperCase field to be based on the title field but the problem is i give an error says: TypeError: Cannot read properties of undefined (reading 'title')

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because you are using an arrow function, the "this" keyword is not what you want it to be. Basically, whenever you are using mongoose hooks like a pre save hook in this case, you should always use a normal function for a callback.

 PostSchema.pre('save', function(next) {
    this.titleUpperCase = this.title.toUpperCase()
    next()
})

I believe this should work.

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