hi am making models for my mongodb , and when validating i want the birthday to be required only if the user being added is a student
so i if the user is teacher it is fine if no birthday is provided
const userSchema = mongoose.Schema({
20
21 _id: mongoose.Schema.Types.ObjectId,
22
23 firstName: {
24 type: String,
25 required: [true, 'the firstName is missing'],
26 validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid first name'],
27 },
28 lastName: {
29 type: String,
30 required: [true, 'the lastName is missing'],
31 validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid last name'],
32 },
33 birthday: {
34 type: Number,
35 required: [true, 'birthday is missing']
36 validate: [(val) =>
37 phoneNumber: {
38 type: String,
39 required: [true, 'the phoneNumber is missing'],
40 unique: [true, 'phoneNumber already in use'],
41 validate: [(val) => validator.isMobilePhone(val,['ar-DZ']), 'not valid phone number'],
42 },
43 email : {
44 type: String,
45 required: [true, 'the email is missing'],
46 unique: [true, 'email already in use'],
47 validate: [validator.isEmail, 'not valid email'],
48 },
49 password: {
50 type: String,
51 required: [true, 'the password is missing'],
52 minlength: [10, 'error when generating a password for the user'],
53 },
54 role: {
55 type : String,
56 "enum" : ['teacher', 'student'],
57 required : [true, 'the user `s role is missing'],
58 },
2
Answers
The
required
property can also accept a function. For example:You can create a function to validate the value of the
role
and use it as a boolean value inrequired
property.