【问题标题】:How to Create and Use Enum in Mongoose如何在 Mongoose 中创建和使用枚举
【发布时间】:2015-05-31 17:02:21
【问题描述】:

我正在尝试在 Mongoose 中创建和使用 enum 类型。我检查了它,但我没有得到正确的结果。我在我的程序中使用enum,如下所示:

我的架构是:

var RequirementSchema = new mongooseSchema({
   status: {
        type: String,
        enum : ['NEW','STATUS'],
        default: 'NEW'
    },
})

但是我在这里有点困惑,我怎样才能把enum 的值放在Java NEW("new") 中。如何根据它的可枚举值将enum 保存到数据库中。我在 express node.js 中使用它。

谢谢

【问题讨论】:

  • 这个问题有大量修正 OP 的错字,从而解决了问题,这使得接受的答案有点混乱。请考虑写入的原始数组缺少“'”:enum: ['NEW, 'STATUS']

标签: node.js mongodb express enums


【解决方案1】:

这里的枚举基本上是 String 对象。将枚举行改为enum: ['NEW', 'STATUS']。你的引号有错别字。

【讨论】:

  • 如何将它链接到用户表?我的不行。我的用户表我插入了这个角色:{ type: mongoose.Schema.Types.ObjectId, ref: 'roles', },
  • 确切地说,您在这里展示的是一个字符串数组,而不是“字符串对象”。
【解决方案2】:

Enums 是 String 对象,例如:enum :['a','b','c'] 或可能像这样 const listOfEn = ['a','b','c']; => enum: listOfEn

【讨论】:

    【解决方案3】:

    来自docs

    Mongoose 有几个内置的验证器。字符串将 enum 作为验证器之一。 因此 enum 创建了一个验证器并检查该值是否在数组中给出。 例如:

    var userSchema = new mongooseSchema({
       userType: {
            type: String,
            enum : ['user','admin'],
            default: 'user'
        },
    })
    
    

    【讨论】:

    • 感谢它对我存储默认用户类型有用。 js如何将userType改为amdin?
    • 如何将它链接到用户表?我的不行。我的用户表我插入了这个角色:{ type: mongoose.Schema.Types.ObjectId, ref: 'roles', },
    【解决方案4】:

    假设我们有一个枚举 Role 定义为

    export enum Role {
      ADMIN = 'ADMIN',
      USER = 'USER'
    }
    

    我们可以像这样使用它:

    {
        type: String,
        enum: Role,
        default: Role.USER,
    }
    

    【讨论】:

    • 在 NestJs 7 上正确测试和验证 ^
    • 如果使用数组,请使用roles: { type: [String], enum: Role, required: true, default: Role.DEFAULT }
    【解决方案5】:

    如果您想使用 TypeScript enum,您可以在接口 IUserSchema 中使用它,但在 Schema 中您必须使用 array (Object.values(userRole))。

    enum userRole {
        admin = 'admin',
        user = 'user'
    }
    
    interface IUserSchema extends Document {
        userType: userRole
    }
    
    const UserSchema: Schema = new Schema({
        userType: {
            type: String,
            enum: Object.values(userRole),
            default: userRole.user, 
            required: true
        }
    });
    

    【讨论】:

      【解决方案6】:

      在 Schema 设计中,您可以使用 enum 关键字轻松添加枚举值,如下所示:-

      catagory: {
          type: String,
          enum: ['freeToPlay','earlyAccess','action','adventure','casual','indie','massivelyMultiplayer','racing','simulation','RPG','sports','statigy'],
          default: 'freeToPlay'
      },
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 2020-03-03
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多