【问题标题】:Mongoose OR schema validationMongoose OR 模式验证
【发布时间】:2013-11-13 17:59:46
【问题描述】:

我有一个字段,它将是两个对象之一(存储的信用卡或给定的信用卡):

  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 构造?

【问题讨论】:

  • 数据如何“通过”?在运行时如何确定哪个是哪个?

标签: node.js mongodb validation mongoose schema


【解决方案1】:

您没有提供包含架构的示例,但是有多种验证方法。

我做的一件事是为 Schema 指定“混合”类型,允许将任何类型用于可能包含任一类型的字段。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2015-09-14
    • 1970-01-01
    • 2016-05-07
    • 2022-01-15
    相关资源
    最近更新 更多