简体   繁体   English

将 mongoose 模式类型限制为字符串枚举

[英]Limit mongoose schema type to string enum

I have this mongoose schema:我有这个 mongoose 架构:

const roles = {
    USER: 'user',
    OWNER: 'owner',
    ADMIN: 'admin'
};


let userSchema = Schema({
           role:
            {
                type: String,
                required: true,
                default: roles.USER
            },
});

I want to limit the type of "role" to only strings from the "roles" object.我想将“角色”的类型限制为仅来自“角色”object 的字符串。 Is there any way I can do this?有什么办法可以做到这一点吗? Thanks in advance!提前致谢!

I believe using a Enum in Mongoose is what you are looking for我相信在 Mongoose 中使用枚举是您正在寻找的

export enum Roles {
  ADMIN = 'admin',
  USER = 'user',
  OWNER = 'owner',
};

let userSchema = Schema({
       role:
       {
           type: String,
           enum : Roles,
           required: true,
           default: Roles.USER
       },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM