如何根据特定条件在猫鼬验证中创建错误数组?
how to create array of errors in mongoose validation based on certain conditions?
我正在尝试根据特定条件生成错误数组,我该如何实现,邮递员指出:“无法读取未定义的属性(读取 'push')”
username: {
type: String,
required: [true, "username is required"],
// minlength: 6,
unique: true,
// match: [
// /^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/,
// "username shouldn't include . or _ and at least 3 letters and at maximum 20 letters",
// ],
validate: {
errors: [],
validator: function (username) {
if (username.length < 10) {
this.errors.push("username cannot be less than 3 characters");
}
if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/)) {
this.errors.push(`username shouldn't begin or end with . or _ `);
}
},
message: this.errors,
},
},
在 validator
函数中创建一个 array
并将此数组 throw
作为 new Error()
。然后在save()
函数的回调中使用这个数组。
validate
validate: {
validator: function (username) {
let errors = []
if (username.length < 3)
errors.push("username cannot be less than 3 characters")
if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/))
errors.push("username shouldn't begin or end with . or _ ")
if (errors.length > 0)
throw new Error(errors)
}
}
save
newUser.save((err, user) => {
if (err) {
let errors = Object.values(err.errors)[0].properties.message.split(',')
return res.status(400).json({
success: false,
err: errors.length > 1 ? errors : errors[0]
})
}
else ...
})
我正在尝试根据特定条件生成错误数组,我该如何实现,邮递员指出:“无法读取未定义的属性(读取 'push')”
username: {
type: String,
required: [true, "username is required"],
// minlength: 6,
unique: true,
// match: [
// /^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/,
// "username shouldn't include . or _ and at least 3 letters and at maximum 20 letters",
// ],
validate: {
errors: [],
validator: function (username) {
if (username.length < 10) {
this.errors.push("username cannot be less than 3 characters");
}
if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/)) {
this.errors.push(`username shouldn't begin or end with . or _ `);
}
},
message: this.errors,
},
},
在 validator
函数中创建一个 array
并将此数组 throw
作为 new Error()
。然后在save()
函数的回调中使用这个数组。
validate
validate: {
validator: function (username) {
let errors = []
if (username.length < 3)
errors.push("username cannot be less than 3 characters")
if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/))
errors.push("username shouldn't begin or end with . or _ ")
if (errors.length > 0)
throw new Error(errors)
}
}
save
newUser.save((err, user) => {
if (err) {
let errors = Object.values(err.errors)[0].properties.message.split(',')
return res.status(400).json({
success: false,
err: errors.length > 1 ? errors : errors[0]
})
}
else ...
})