Jac*_*son 4 javascript enums mongoose mongodb node.js
我需要在架构中获取字段的枚举值
我有架构:
let adminSchema = new Schema({
login: {
type: String,
unique: true,
required: true,
minlength: 5,
maxlength: 300
},
hashedPassword: {
type: String
},
role: {
type: Number,
enum: [0, 1, 2],
default: 1
},
salt: {
type: String
}
});
module.exports.Admin = Admin;
module.exports.roleEnum = Admin.schema.path('role').enumValues;
console.log(module.exports.roleEnum);
Run Code Online (Sandbox Code Playgroud)
控制台日志 -> 未定义
但是如果我将角色字段类型更改为字符串
let adminSchema = new Schema({
login: {
type: String,
unique: true,
required: true,
minlength: 5,
maxlength: 300
},
hashedPassword: {
type: String
},
role: {
type: String,
enum: ['0', '1', '2'],
default: '1'
},
salt: {
type: String
}
});
module.exports.Admin = Admin;
module.exports.roleEnum = Admin.schema.path('role').enumValues;
console.log(module.exports.roleEnum);
Run Code Online (Sandbox Code Playgroud)
控制台日志 -> ['0', '1', '2'];
我如何获得数字类型的枚举数组?
要指定数值范围,您可以在架构中定义min
和max
值:
role: {
type: Number,
min: 0,
max: 2,
default: 1
},
Run Code Online (Sandbox Code Playgroud)
文档在这里。
还要求这些值是整数,请参见此处。