Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB field only accepts 3 special values

      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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading