Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!