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

169

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

我的模式为:

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

但是我在这里有一点点困惑,我该如何像在Java中的NEW("new")那样放置一个enum的值。根据其可枚举的值,我该如何将enum保存到数据库中。我正在使用express node.js。


23
这个问题有很多次修订,纠正了提问者的拼写错误并解决了问题,这使得被接受的答案有点令人困惑。请注意,原来的数组缺少一个引号:enum: ['NEW, 'STATUS'] - Alvaro Carvalho
6个回答

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

你如何将它与用户表关联起来?我的不起作用。在我的用户表中,我插入了这个角色:{ type: mongoose.Schema.Types.ObjectId, ref: 'roles', }。 - Grizzly Bear
准确来说,你在这里展示的是一个字符串数组,而不是一个“字符串对象”。 - matewka

134

来自文档

Mongoose有几个内置验证器。其中字符串拥有枚举(enum)作为之一的验证器。 所以,枚举创建了一个验证器并检查值是否给定在一个数组中。 例如:

const userSchema = new mongoose.Schema({
   userType: {
        type: String,
        enum : ['user','admin'],
        default: 'user'
    },
})


谢谢,这对我来说可以存储默认的用户类型。如何从js更改用户类型为管理员? - Qui-Gon Jinn
你如何将它与用户表关联起来?我的不起作用。我在用户表中插入了这个 role: { type: mongoose.Schema.Types.ObjectId, ref: 'roles', }, - Grizzly Bear

47
假设我们有一个枚举类型Role,定义如下:
export enum Role {
  ADMIN = 'ADMIN',
  USER = 'USER'
}

我们可以将它用作类型,例如:
{
    type: String,
    enum: Role,
    default: Role.USER,
}

1
在NestJs 7上进行了适当的测试和验证。 - xIsra
3
建议使用数组,而不是使用roles: { type: [String], enum: Role, required: true, default: Role.DEFAULT } - Gaspar

18

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

<code><code><code>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
    }
});
</code></code></code>

10

枚举是字符串对象,例如:enum :['a','b','c'] 或者可能像这样:const listOfEn = ['a','b','c']; => enum: listOfEn


6
在 Schema 设计中,你可以使用 enum 关键字轻松添加一个枚举值,例如:-
catagory: {
    type: String,
    enum: ['freeToPlay','earlyAccess','action','adventure','casual','indie','massivelyMultiplayer','racing','simulation','RPG','sports','statigy'],
    default: 'freeToPlay'
},

您的答案可以通过添加支持信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心中找到有关撰写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接