0

Lets say I have this schema.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TestSchema = new Schema({
  language: {
  required: true,
  default: 'eng',
  },
});

// Compile model from schema
const TestModel = mongoose.model("Test", TestSchema);

How can I configure this schema so that language field will only accept its value as eng or hbrw. If it recievs some other value it would return an error.

I know it can be done explicitly with if else but I want to know if it can be built into the schema.

1 Answers1

0

This is how its done:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TestSchema = new Schema({
  language: {
    required: true,
    enum: ['eng', 'hbrw']
    default: 'eng',
  },
});

// Compile model from schema
const TestModel = mongoose.model("Test", TestSchema);

Enum field validates the coming data against the array of data given in enum field.

Thanks @turivishal for this solution