I am making a model for MongoDB with mongoose. I am leaning with Typescript to define it. I have a problem because when I declare a property and I want to insert a validation function referring to another property, TS throws me an error
Property 'gender' does not exist on type 'SchemaTypeOpts | scheme | SchemaType'. Property 'gender' does not exist on type 'Schema'.ts(2339)
this is my code
import mongo from 'mongoose'
const schema = new mongo.Schema({
name: {
type: String,
match: [ /^[a-zA-Z]{2,35}$/,
'El es requerido y debe tener una longitud de 2-35 caracteres' ]
},
lastName: {
type: String,
match: [ /^[a-zA-Z]{2,50}$/,
'El es requerido y debe tener una longitud de 2-50 caracteres' ]
},
email: {
type: String,
unique: [ true, 'Ya existe un correo electrónico registrado' ],
match: [ /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
'El formato del correo es incorrecto'
]
},
userName: {
type: String,
unique: [ true, 'Ya existe este nombre de usuario'],
match: [ /^[a-zA-Z]{5,15}$/,
'El es requerido y debe tener una longitud de 5-15 caracteres' ]
},
phoneNumber: {
type: Number,
match: [ /^[0-9]{10}$/,
'El formato del número telefónico es incorrecto' ]
},
gender: {
type: String,
enum: ['H', 'M'],
default: 'H'
},
department: {
type: mongo.Schema.Types.ObjectId, ref: 'Department'
},
role: {
type: mongo.Schema.Types.ObjectId, ref: 'Role'
},
photo: {
type: String,
default: function() {
return this.gender === 'M' ? 'profile_male.png' : 'profile_female.png'
}
},
sign: {
type: String,
required: [ true, 'Fatal: No se creo correctamente la contraseña']
},
status: {
type: String,
enum: ['activo', 'inactivo'],
default: 'activo'
},
createdBy: {
type: mongo.Schema.Types.ObjectId, ref: 'User'
},
createdDate: {
type: Date,
default: Date.now
},
changes: [
{
date: { type: Date, default: Date.now },
user: { type: mongo.Schema.Types.ObjectId, ref: 'User' }
}
]
}, { collection: 'users' })
export const UserModel = mongo.model( 'User', schema )
I tried to do this example validation in official mongoose documentation
According to the mongoose documentation:
Save/Validate Hooks
To achieve what you want you must define a pre hook:
More information here