如何在 Mongoose 中创建和使用枚举

新手上路,请多包涵

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

我的架构是:

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

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

谢谢

原文由 Prabjot Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 948
2 个回答

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

原文由 Mindstormer619 发布,翻译遵循 CC BY-SA 3.0 许可协议

If you would like to use TypeScript enum you can use it in interface IUserSchema but in Schema you have to use 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
    }
});

原文由 Jax-p 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题