I need to get enum values of field in schema
I have schema:
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);
I need to get enum values of field in schema
I have schema:
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);
console log -> undefined
but if i change role field type to String
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);
console log -> ['0', '1', '2'];
How i can get enum array in Number type??
Share Improve this question asked Feb 17, 2017 at 17:15 JacksonJackson 9143 gold badges13 silver badges25 bronze badges3 Answers
Reset to default 12To specify a range of numeric values, you can define min
and max
values in the schema:
role: {
type: Number,
min: 0,
max: 2,
default: 1
},
Docs here.
To also require that the values are integers, see here.
The enums here are basically String objects. They can be Numbers
All SchemaTypes have the built-in required validator.The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator.
Numbers have enum, min and max validators.
Strings have enum, match, maxlength and minlength validators.
Reference
You can get integer enums in schema.path('some_path').options.enum;
as mentioned in Docs here