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')

Answer

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.