只有当用户是确定的值时,如何使required为true



hi正在为我的mongodb制作模型,在验证时,我希望只有当添加的用户是学生时才需要生日所以我如果用户是老师,如果没有提供生日也没关系

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         },

required属性也可以接受函数。例如:

required: [
function () { return this.role === 'student'; },
'birthday is missing'
]

您可以创建一个函数来验证role的值,并将其用作required属性中的布尔值

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var userSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
firstName: {
type: String,
required: [true, 'the firstName is missing'],
validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid first name'],
},
role: {
type: String,
enum: ['teacher', 'student'],
required: [true, 'the user `s role is missing'],
},
birthday: { type: Number, required: [isBirthdayRequired, 'the birthday is missing'] },
});

function isBirthdayRequired() {
if (this.role === 'student') {
return true;
}
return false;
}

相关内容

最新更新