我有一个字段,它将是两个对象之一(存储的信用卡或给定的信用卡):
payment_method:
cc_token: String
security_code: String
payment_method:
number: String
security_code: String
expiration_month: Number
expiration_year: Number
billing_address:
_type: String
first_name: String
last_name: String
address_line1: String
address_line2: String
zip_code: String
city: String
state: String
phone_number: String
我知道传递的数据将匹配其中之一,但不会同时匹配两者。有没有一种方法可以为验证指定某种 OR 结构?
最佳答案
您没有提供包含架构的示例,但是有多种验证方法。
我做的一件事是为架构指定“混合”类型,允许任何类型用于可能包含任一类型的字段。
function validatePaymentMethod(value) {
if (!value) { return false; }
// put some logic that checks for valid types here...
if (value.cc_token && value.billing_address) {
return false;
}
return true;
}
var OrderSchema = new mongoose.Schema({
payment_method : { type: mongoose.Schema.Types.Mixed,
validate: [validatePaymentMethod, 'Not valid payment method'] }
});
var Order = mongoose.model("Order", OrderSchema);
var o = new Order();
o.payment_method = { cc_token: 'abc', billing_address: 'Street' };
o.validate(function(err) {
console.log(err);
});
其他的都记录了here .
关于node.js - Mongoose OR 模式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745329/