Home > Blockchain >  MongoDB field only accepts 3 special values
MongoDB field only accepts 3 special values

Time:03-28

      slider_value: {
        type: Number,
        required: false,
      },

This is the Mongoose schema for one of the fields in my MongoDB model.

It may only accept the integer values of 1, 4, and 10.

How can this validator be specified in the schema?

CodePudding user response:

If you only need to store either one of these three values, storing them as a string, and validating using the enum key would be reasonable. For example that could look like this:

{
  slider_value: {
    type: String,
    enum: ["1", "4", "10"],
  },
}

Alternatively, if it is a requirement to store them in form of an int, you could use a custom validator to check a value before it's saved. That would look like this:

{
  slider_value: {
    type: Number,
    validate: {
      validator: value => value === 1 || value === 4 || value === 10,
      message: props => `${props.value} is invalid for slider_value`,
    },
  },
}

For more details on custom validators and validation in mongoose in generell, here are the mongoose validation docs.

  • Related