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.
Enum types cannot be nullable.
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' }, })
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.
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]),
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With