Emmanuel Amodu
Emmanuel Amodu

Reputation: 197

How to change enum values in Mongoose

I have a enum property in my mongoose collection that was initial defined as const actions = ['a', 'b', 'c'] I have a requirement to change it to add addition actions const actions = ['a', 'b', 'c', 'd', 'e'] to the enum but when I try to use the additional values i.e. action = 'e' I get a validation error "Model validation failed: action: 'e' is not a valid enum value for path 'action'."

My question is how do I add additional values to the enum to a mongo collection in mongoose already in production.

mongoose.model('Model', new Schema({
  action: {
    type: String,
    required: true,
    enum: actions,
    immutable: true
  }}))

Upvotes: 1

Views: 1481

Answers (1)

Brian Vu
Brian Vu

Reputation: 19

Due to inconsistent between current and previous data, Mongoose will try to validate current data (old schema) with the new one, even when you don't modify anything and cause a validation error. In my case, I force Mongoose to save with new schema by using flag validateBeforeSave.

For example:

const savedProduct = await currentProduct.save({ validateBeforeSave: false });

Upvotes: 1

Related Questions