Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 387
Marik Sh Avatar asked Sep 01 '20 10:09

Marik Sh


People also ask

Is enum Nullable?

Enum types cannot be nullable.

What is enum in Mongoose schema?

Mongoose has several inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array. E.g: const userSchema = new mongoose. Schema({ userType: { type: String, enum : ['user','admin'], default: 'user' }, })

What is ObjectId in Mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.


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

...
like image 196
Ali Tavafi Avatar answered Sep 21 '22 04:09

Ali Tavafi