how to allow nullable for an enum field in mongoose schema?

Viewed 4011

I'm trying to create a new object in MongoDB using mongoose.

Here is my mongoose schema:

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",
}

When I'm trying to create a new user using:

model.create({
 email: 'some@email.com',
}).exec()

The following error throws:

users validation failed: someKey: `null` is not a valid enum value for path `someKey`., 

I was able to fix this by setting:

enum: [...Object.values(SomeEnumObj), null]

But I was wondering if there is a better or more right way of doing this as my solution feels a little hacky, and I expect that if I set the default to null, the validator will allow this to be null.

1 Answers

Based on this issue I also didn't find any proper solution as this is my problem too. I believe there is no need to add null as the default value (default: null) to fix the problem.

Just add this to your schema:

Object.values(SomeEnumObj).concat([null])

Your schema :

...

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

...
Related