Mongoose 枚举数

Jac*_*son 4 javascript enums mongoose mongodb node.js

我需要在架构中获取字段的枚举值

我有架构:

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);
Run Code Online (Sandbox Code Playgroud)

控制台日志 -> 未定义

但是如果我将角色字段类型更改为字符串

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);
Run Code Online (Sandbox Code Playgroud)

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

我如何获得数字类型的枚举数组?

Joh*_*yHK 8

要指定数值范围,您可以在架构中定义minmax值:

role: {
    type: Number,
    min: 0,
    max: 2,
    default: 1
},
Run Code Online (Sandbox Code Playgroud)

文档在这里

还要求这些值是整数,请参见此处


Asi*_*eed 6

这里的枚举基本上是 String 对象。它们可以是数字

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

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

  • 字符串具有枚举、匹配、最大长度和最小长度验证器。

参考