Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 221
Jackson Avatar asked Dec 08 '22 19:12

Jackson


2 Answers

To 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.

like image 65
JohnnyHK Avatar answered Dec 11 '22 08:12

JohnnyHK


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

like image 37
Asif Saeed Avatar answered Dec 11 '22 10:12

Asif Saeed