I am trying to define a conditional required field for a mongoose model in the following way:
const userSchema = new mongoose.Schema({
email: {
type: String,
},
emailVerified: {
type: Boolean,
required: true
},
hash: {
type: String,
required: function() {
if(!this.emailVerified) return true
return false
}
},
oauth: {
type: Boolean,
required: true,
},
password: {
type: String,
required: function() {
if(this.oauth) return false
return true
}
}
})
export default mongoose.models.Users || mongoose.model('Users', userSchema)
My intention is that I only want the hash field to be required when emailVerified === false, and the password field to be required only when oauth === true.
The thing is that when I try to add a document in the Users collection I get the following error:
Error: Users validation failed: hash: Cannot read property 'emailVerified' of undefined, password: Cannot read property 'oauth' of undefined
By looking at the documentation I understand that I should be able to reference the model in its own definition.