2014-09-22 24 views
4

我有這個模式,我驗證了數組0123'的元素,但我不知道如何驗證數組本身。如何在Mongoose數組中驗證其同時其元素

var DictionarySchema = new Schema({ 
     book: [ 
      {    
       1: { 
        type: String, 
        required: true 
       }, 
       2: String, 
       3: String, 
       c: String, 
       p: String, 
       r: String 
      } 
     ] 
    }); 

例如,我想根據需要放入書籍數組。任何幫助?

回答

8

您可以使用custom validator來執行此操作。簡單地檢查陣列本身不爲空:

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema; 

mongoose.connect('mongodb://localhost/test'); 

var bookSchema = new Schema({ 

    1: { type: String, required: true }, 
    2: String, 
    3: String, 
    c: String, 
    p: String, 
    r: String 
}); 

var dictSchema = new Schema({ 
    books: [bookSchema] 
}); 

dictSchema.path('books').validate(function(value) { 
    return value.length; 
},"'books' cannot be an empty array"); 

var Dictionary = mongoose.model('Dictionary', dictSchema); 


var dict = new Dictionary({ "books": [] }); 


dict.save(function(err,doc) { 
    if (err) throw err; 

    console.log(doc); 

}); 

當有數組中沒有含量將拋出一個錯誤,否則通關爲數組中的字段提供規則的驗證。

+0

謝謝,這非常有用!!!但是,還有另一種方法可以將驗證內聯傳遞給數組'book'。因爲有時需要使用其他不同的過濾器來處理''required',例如('max','min','expires','enum','小寫字母','match','trim','uppercase'等)已經由貓鼬提供了,我認爲這可能是低效率的,在'validate()'函數中實現它。 – in3pi2 2014-09-22 03:30:10

+2

@ in3pi2無論如何,對於所有內置的類型和規則來說,這是如何進行驗證的,並且mongoose API只是暴露內部方法,因此您可以「插入」它。另請參閱文檔中的[plugins](http://mongoosejs.com/docs/plugins.html)。 – 2014-09-22 03:36:19

+1

@ in3pi2因爲貓鼬默認會這樣做。你可以關掉它。通讀文檔,如果你有其他問題,然後問另一個問題,而不是發表評論。 – 2014-09-22 04:36:33

相關問題