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

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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