2017-02-17 49 views
1

我需要在架構貓鼬枚舉數

場的枚舉值我有模式:

let adminSchema = new Schema({ 
 
\t login: { 
 
\t \t type: String, 
 
\t \t unique: true, 
 
\t \t required: true, 
 
\t \t minlength: 5, 
 
\t \t maxlength: 300 
 
\t }, 
 
\t hashedPassword: { 
 
\t \t type: String 
 
\t }, 
 
\t role: { 
 
\t \t type: Number, 
 
\t \t enum: [0, 1, 2], 
 
\t \t default: 1 
 
\t }, 
 
\t salt: { 
 
\t \t type: String 
 
\t } 
 
}); 
 

 
module.exports.Admin = Admin; 
 
module.exports.roleEnum = Admin.schema.path('role').enumValues; 
 
console.log(module.exports.roleEnum);

控制檯日誌 - >未定義

但如果我改變角色字段類型爲字符串

let adminSchema = new Schema({ 
 
\t login: { 
 
\t \t type: String, 
 
\t \t unique: true, 
 
\t \t required: true, 
 
\t \t minlength: 5, 
 
\t \t maxlength: 300 
 
\t }, 
 
\t hashedPassword: { 
 
\t \t type: String 
 
\t }, 
 
\t role: { 
 
\t \t type: String, 
 
\t \t enum: ['0', '1', '2'], 
 
\t \t default: '1' 
 
\t }, 
 
\t salt: { 
 
\t \t type: String 
 
\t } 
 
}); 
 

 
module.exports.Admin = Admin; 
 
module.exports.roleEnum = Admin.schema.path('role').enumValues; 
 
console.log(module.exports.roleEnum);

控制檯日誌 - > [ '0', '1', '2'];

我怎樣才能得到enum數組類型?

回答

2

要指定一個數值範圍,你可以在模式中定義minmax值:

role: { 
    type: Number, 
    min: 0, 
    max: 2, 
    default: 1 
}, 

文檔here

要還要求值是整數,請參閱here

2

這裏的枚舉基本上是String對象。他們不能是數字

  • 所有SchemaTypes有內置的要求validator.The需要驗證程序使用的SchemaType的checkRequired()函數來確定的值滿​​足要求的驗證。

  • 數字有最小和最大驗證碼。

  • 字符串具有枚舉,匹配,最大長度和最小長度驗證程序。