2016-05-30 41 views
0

我正在使用類似於以下模式的內容。
通過訪問項目頁面我可以添加相關項目到項目的相關項目數組字段。自定義驗證對象推送到數組

我想定製驗證到項目的相關信息領域,以測試是否數組中存在類似的對象已經是對象 - 所以,我沒有得到重複。

在我的代碼下面,自定義驗證不會觸發。我期望這可能是因爲自定義驗證不能應用於type: [object],並且應該應用於對象的屬性 - 但是然後我無法將該對象作爲一個整體進行測試。

const ItemsSchema = new SimpleSchema({ 
    name: { 
    type: String, 
    label: 'Name', 
    }, 
    related: { 
    type: [Object], 
    label: 'Related Items', 
    optional:true, 
    custom: function() { 
     let queryData = { docId: this.docId, related: this.value } 
     if (Meteor.isClient && this.isSet) { 
     Meteor.call("relatedObjectIsUniqueForThisItem", queryData, 
     function (error, result) { 
      if(!result){ 
      console.log("not unique"); 
      return "Invalid"; 
      } 
      else{ 
      return true; 
      } 
     }); 
     } 
    } 

    }, 
    'related.$.name':{ 
    type: String, 
    label:'Name', 
    }, 
    'related.$.code':{ 
    type:String, 
    label:'Code', 
    min:5, 
    }, 
}); 

回答

0

我想出瞭解決這個問題的方法。

自定義驗證不應位於[對象]上,而應該是對象的屬性之一 - 在本例中爲「源」或「代碼」。

在其中一個對象屬性中,你可以調用this.siblingField(otherField);但它意味着你必須重建對象。

在我的情況: -

const ItemsSchema = new SimpleSchema({ 
    name: { 
    type: String, 
    label: 'Name', 
    }, 
    related: { 
    type: [Object], 
    label: 'Related Items', 
    optional:true, 
    }, 
    'related.$.name':{ 
    type: String, 
    label:'Name', 
    custom: function() { 

    //--------------------------- 
    //this is the important bit 
    //--------------------------- 
     let queryData = { 
      docId: this.docId, 
      related: { 
       name:this.value, 
       code:this.siblingField('code').value, 
      } 
     } 

     //--------------------------- 
    //end of important bit 
    //--------------------------- 

     if (Meteor.isClient && this.isSet) { 
     Meteor.call("relatedObjectIsUniqueForThisItem", queryData, 
     function (error, result) { 
      if(!result){ 
      console.log("not unique"); 
      return "Invalid"; 
      } 
      else{ 
      return true; 
      } 
     }); 
     } 
    } 

    }, 
    'related.$.code':{ 
    type:String, 
    label:'Code', 
    min:5, 
    }, 
});