【问题标题】:Mongoose Enum NumberMongoose 枚举数
【发布时间】:2017-07-07 07:46:14
【问题描述】:

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

我有架构:

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

控制台日志 -> 未定义

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

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 类型的枚举数组??

【问题讨论】:

    标签: javascript node.js mongodb mongoose enums


    【解决方案1】:

    您可以在schema.path('some_path').options.enum; 中获取整数枚举 如文档here中所述

    【讨论】:

      【解决方案2】:

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

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

      文档here.

      还要求值是整数,请参阅here

      【讨论】:

        【解决方案3】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 2021-01-21
          • 2022-12-17
          • 2019-01-30
          • 1970-01-01
          • 2013-12-16
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 2021-09-01
          相关资源
          最近更新 更多