猫鼬号码

时间:2017-02-17 17:15:06

标签: javascript node.js mongodb mongoose enums

我需要在模式中获取字段的枚举值

我有架构:

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);

控制台日志 - >未定义

但是如果我将角色字段类型更改为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);

控制台日志 - > ['0','1','2'];

如何在Number类型中获取枚举数组?

3 个答案:

答案 0 :(得分:4)

要指定一系列数值,您可以在架构中定义minmax值:

role: {
    type: Number,
    min: 0,
    max: 2,
    default: 1
},

文档here

要同时要求值为整数,请参阅here

答案 1 :(得分:2)

这里的枚举基本上是String对象。他们不能成为数字

  • 所有SchemaTypes都有内置的必需验证器。所需的验证器使用SchemaType的checkRequired()函数来确定该值是否满足所需的验证器。

  • 数字有最小和最大验证器。

  • 字符串包含枚举,匹配,最大长度和最小长度验证器。

答案 2 :(得分:2)

您可以在if col4==ronaldo, go to table 1 if col4==bravo and col3==mun, go to table 2 if col4==bravo and col3 ==sign go to table 3中获得整数枚举 如文档here

中所述