Marik Sh
Marik Sh

Reputation: 731

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

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: '[email protected]',
}).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.

Upvotes: 12

Views: 11432

Answers (2)

Ali Tavafi
Ali Tavafi

Reputation: 533

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]),
}

...

UPDATE

As stated in the Mongoose@^8 migration guide, null is valid for non-required string enums.

const schema = new Schema({
  status: {
    type: String,
    enum: ['on', 'off']
  }
});
const Test = mongoose.model('Test', schema);

// Works fine in Mongoose 8
// Throws a `ValidationError` in Mongoose 7
await Test.create({ status: null });

Upvotes: 8

David
David

Reputation: 3804

Using undefined rather than null worked for me:

        someKey: {
            type: String,
            default: undefined,
            required: false,
            enum: SomeEnumObj,
        }

Upvotes: 1

Related Questions