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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29299477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:34:14  来源:igfitidea点击:

How to Create and Use Enum in Mongoose

node.jsmongodbexpressenums

提问by Prabjot Singh

I am trying to create and use an enumtype in Mongoose. I checked it out, but I'm not getting the proper result. I'm using enumin my mongoose schema as follows:

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

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

But I am little bit confused here, how can I put the value of an enumlike in Java NEW("new"). How can I save an enumin to the database according to it's enumerable values. I am using it in express node.js.

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

回答by Mindstormer619

The enums here are basically String objects. Change the enum line to enum: ['NEW', 'STATUS']instead. You have a typo there with your quotation marks.

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

回答by Deeksha Sharma

From the docs

文档

Mongoose has several inbuilt validators. Strings have enumas one of the validators. So enum creates a validator and checks if the value is given in an array. E.g:

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

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

回答by hien711

Enums is String objects so for example : enum :['a','b','c']or probably like this const listOfEn = ['a','b','c']; => enum: listOfEn

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