最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose Enum Number - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 12

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.

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

发布评论

评论列表(0)

  1. 暂无评论