Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading