2014-07-23 58 views
1

我在Mongoose中使用Schema作爲子文檔,但我無法在其字段中驗證它。
這就是我驗證Mongoose中的子文檔

var SubdocumentSchema = new Schema({ 
    foo: { 
     type: String, 
     trim: true, 
     required: true 
    }, 
    bar: { 
     type: String, 
     trim: true, 
     required: true 
    } 
}); 

var MainDocumentSchema = new Schema({ 
    name: { 
    type: String, 
    trim: true, 
    required: true 
    }, 
    children: { 
    type : [ SubdocumentSchema.schema ], 
    validate: arrayFieldsCannotBeBlankValidation 
    } 
}); 

我想肯定的是,子文檔的每個字段不爲空。
我發現這不可能用標準方法來驗證數組,所以我寫了我的自定義驗證函數。 現在我必須手動檢查所有的字段是正確的而不是空的,但它看起來像一個不是真正可擴展的解決方案,所以我想知道是否有一些本地方法從MainDocument觸發子文檔驗證。

回答

4

children的定義,它應該是[SubdocumentSchema],不[SubdocumentSchema.schema]

var MainDocumentSchema = new Schema({ 
    name: { 
    type: String, 
    trim: true, 
    required: true 
    }, 
    children: { 
    type : [ SubdocumentSchema ], 
    validate: arrayFieldsCannotBeBlankValidation 
    } 
}); 

SubdocumentSchema.schema計算結果爲undefined所以在當前的代碼貓鼬不具備必要的類型信息來驗證的children的元素。

+0

謝謝你。我搞亂了一切,試圖在數組上運行自定義驗證,認爲問題出在那裏,而這正是我調用模式的方式。你救了我。 – pasine