2017-10-18 67 views
2

我有這個moongoose模式:貓鼬架構編號字段是在精確長度

var userSchema = new mongoose.Schema({ 
    firstname: { 
     type: String, 
     required: true, 
     min: 3, 
     max: 24 
    }, 

    lastname: { 
     type: String, 
     required: true, 
     min: 3, 
     max: 24 
    }, 

    id: { 
     type: Number, 
     required: true, 
     min: 9, 
     max: 9 
    }, 

    mediations: [assetSchema] 
}); 

當我嘗試添加新的用戶id爲我獲得下一個驗證錯誤:

{ 
    "errors": { 
     "id": { 
      "message": "Path `id` (320981350) is more than maximum allowed value (9).", 
      "name": "ValidatorError", 
      "properties": { 
       "max": 9, 
       "type": "max", 
       "message": "Path `{PATH}` ({VALUE}) is more than maximum allowed value (9).", 
       "path": "id", 
       "value": 320981350 
      }, 
      "kind": "max", 
      "path": "id", 
      "value": 320981350, 
      "$isValidatorError": true 
     } 
    }, 
    "_message": "User validation failed", 
    "message": "User validation failed: id: Path `id` (320981350) is more than maximum allowed value (9).", 
    "name": "ValidationError" 
} 

是否有任何其他方式來驗證Number類型字段的準確長度? 還是我誤解了貓鼬店的數字?

回答

2

minmax意味着允許的數字量提供的Number,因爲錯誤說:

(320981350) is more than maximum allowed value (9)

他們的意思是該領域的實際最小值/最大值與Number類型,因此,例如在

{ 
    type: Number, 
    min : 101, 
    max : 999 
} 
  • 最大Number所有欠是999
  • 允許的最小Number101

在你的情況,如果你有9位數字作爲您id,在架構定義如下領域:

{ 
    type: Number, 
    min : 100000000, 
    max : 999999999 
} 
0

minmax並不意味着min-lengthmax-length ...

所以要達到您的目標,您最好將此設置爲喲UR模式:

{ 
    type: Number, 
    min: 100000000, 
    max: 999999999 
} 

看看貓鼬文檔: mongoose Doc