Mongoose或架构验证

3

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

  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

我知道传递的数据只会匹配其中一种,而不是两种。是否有一种方式可以指定某种或构造用于验证?


数据是如何"传递"的?在运行时如何确定哪个是哪个? - WiredPrairie
1个回答

1
你没有提供包含模式的示例,但是有许多验证的方法。

我所做的一件事是指定了“混合”类型的模式,允许任何类型用于可以包含任一类型的字段。

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);
});

其他文档可以在这里找到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接