node.js - 如何允许 Mongoose 模式中的枚举字段为空?

标签 node.js mongodb typescript mongoose enums

我正在尝试使用 在 MongoDB 中创建一个新对象 Mongoose .
这是我的 Mongoose 模式:

const UsersSchema = new Schema<BaseUser>(
    {
        email: {
            type: Schema.Types.String,
            index: true,
            required: true,
            unique: true,
        },
        someKey: {
            type: Schema.Types.String,
            default: null,
            required: false,
            enum: Object.values(SomeEnumObj),
        }
    },
    {
        timestamps: true,
    }
);

enum SomeEnumObj = {
 TEST = "TEST",
}
当我尝试使用以下方法创建新用户时:
model.create({
 email: 'some@email.com',
}).exec()
抛出以下错误:
users validation failed: someKey: `null` is not a valid enum value for path `someKey`., 
我能够通过设置来解决这个问题:
enum: [...Object.values(SomeEnumObj), null]
但是我想知道是否有更好或更正确的方法来执行此操作,因为我的解决方案感觉有点笨拙,并且我希望如果我将默认值设置为 null,验证器将允许它为 null。

最佳答案

基于 this issue我也没有找到任何合适的解决方案,因为这也是我的问题。我相信没有必要添加 null 作为 默认值 (default: null)解决问题。
您只能设置 nullable: true在您的架构中并将其编写为更具可读性,如下所示:

Object.values(SomeEnumObj).concat([null])
您的架构:
...

someKey: {
  type: Schema.Types.String,
  nullable: true
  enum: Object.values(SomeEnumObj).concat([null]),
}

...

关于node.js - 如何允许 Mongoose 模式中的枚举字段为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63685706/

相关文章:

javascript - gridsome.server.js 无法识别函数 addCollection

php - 监视并重新启动开发中长时间运行的 PHP 进程 (Ratchet)

c# - 返回 IAsyncCursor 的 MongoDB C# 驱动程序 Mock 方法

javascript - 连接 MEAN 堆栈的 A 和 M 组件 - 需要提示和指导

typescript - 抽象类上的抽象静态方法

typescript - 如何在打开的编辑器中搜索具有给定扩展名的文件?

javascript - 如何让 browserify 的 "bundle"函数发出结束事件?

javascript - JSHint 是否支持异步/等待?

python - pymongo 中 $and 运算符的正确用法是什么?

typescript - 如何使用内部带有 "this"的箭头函数修复此 @typescript-eslint 警告?