我正在尝试从嵌套架构结构中验证电子邮件 ID 模型,但显示错误:-
adminSchema.path('email').validate((val) => {
类型错误:无法读取未定义的属性“验证”
模型结构:-
var adminSchema = new mongoose.Schema({
companyName : {
type: String,
required: "Company name can't be empty.",
required: false
},
companyID: {
type: String,
},
address : {
type: String,
required: "Address can't be empty.",
},
contactDetails : {
type: String,
required: "Company contact number can't be empty.",
},
admin: {
email : {
type: String,
required: "Email can't be empty.",
unique: true
},
password: {
type: String,
required: "First name can't be empty."
},
firstName : {
type: String,
required: "First name can't be empty."
},
lastName : {
type: String,
required: "Last name can't be empty."
},
phoneNumber : {
type: String,
required: "Reqired for further contact. Can't be empty."
},
designation : {
type: String,
required: "Designation can't be empty."
},
verified: {
type: Boolean,
default: false
},
role: String,
emailResetTokenn: String,
emailExpires: Date,
saltSecret: String,//this is user for encryption and decryption of password
users:[{
email : {
type: String,
required: "Email can't be empty.",
unique: true
},
password: {
type: String,
required: "First name can't be empty."
},
firstName : {
type: String,
required: "First name can't be empty."
},
lastName : {
type: String,
required: "Last name can't be empty."
},
phoneNumber : {
type: String,
required: "Reqired for further contact. Can't be empty."
},
verified: {
type: Boolean,
default: false
},
role: String,
emailResetToken: String,
emailExpires: Date,
saltSecret: String //this is user for encryption and decryption of password
}]
}
});
我想验证管理员和用户的电子邮件 ID。
我该如何使其正确?
试图弄清楚我犯的愚蠢错误是什么,但尚未找到
我尝试添加路径adminSchema.admin.path('email').validate((val)
我得到了
adminSchema.admin.path('email').validate((val) => {
^
TypeError: Cannot read property 'path' of undefined
最佳答案
您的adminSchema
不包含字段路径email
,而是admin.email
(或admin.users.$.email
作为子模式),Mongoose 确实将这些路径中的任何一个作为模式实例的属性。
因此添加 validate
中间件的操作如下:
adminSchema.path('admin.email').validate(...)
关于node.js - 验证来自嵌套模式结构 Mongoose 的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219664/