'Mongoose Enum Number
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??
Solution 1:[1]
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.
Solution 2:[2]
You can get integer enums in schema.path('some_path').options.enum;
as mentioned in Docs here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | indianMonk |
| Solution 2 | Piyush Kakkar |
