我正在用猫鼬编写用户模式条目的验证。我想在架构中创建两个必需的条目(密码,googleId)中的任何一个,但并非两个条目都是必需的。我想确保该用户具有密码或googleId。如何做到这一点?以下是我的架构
const UserSchema = new mongoose.Schema({
password: {
type: String,
trim: true,
required: true,
validate: (value)=>
{
if(value.includes(this.uname))
{
throw new Error("Password must not contain username")
}
}
},
googleId: {
type: String,
required: true
}
});
答案 0 :(得分:0)
您可能要做的是添加一个预验证检查,然后调用下一个或使文档无效。
const schema = new mongoose.Schema({
password: {
type: String,
trim: true
},
googleId: {
type: String
}
});
schema.pre('validate', { document: true }, function(next){
if (!this.password || !this.googleId)
this.invalidate('passwordgoogleId'. 'One of the fields required.');
else
next();
});
我还没尝试过。
答案 1 :(得分:0)
您可以使用custom validator:
LOAD DATA LOCAL INFILE 'C:/Users/TEMP/Desktop/tempname.csv' INTO TABLE tempname
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n'
(Name, ID, Birthday)
或使用const UserSchema = new mongoose.Schema({
password: {
type: String,
trim: true,
required: true,
validate: {
validator: checkCredentials,
message: props => `${props.value} is not a valid phone number!`
},
},
googleId: {
type: String,
required: true
}
});
function checkCredentials(value) {
if (!this.password || !this.googleId) {
return false;
}
return true;
}
验证中间件
pre