Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
How to create a mongoose schema to accept only some discreet values

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!