You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Mongoose Schema中枚举值的大小写不敏感校验?

Case-Insensitive Enum Validation in Mongoose

Great question! Handling case-insensitive enum checks in Mongoose is a common pain point, and there are a couple of cleaner approaches than writing a fully custom validator from scratch. Let me break down the best options for you:

The most practical approach is to convert the input value to a consistent case (uppercase or lowercase) before validation and storage. This ensures your enum check works as intended, plus it keeps your database data uniform (no mixed-case values floating around).

Add a set function to your difficulty field:

const quesSchema = new mongoose.Schema({ 
  acRate: { type: Number }, 
  difficulty: { 
    type: String, 
    enum: { 
      values: ['EASY', 'MEDIUM', 'HARD'], 
      message: 'Difficulty should be either EASY, MEDIUM or HARD', 
    },
    // Convert input to uppercase before validation/storage
    set: (value) => value ? value.toUpperCase() : value
  }, 
  title: { type: String }, 
  titleSlug: { type: String }, 
  topicTags: [ { name: { type: String } } ], 
});

Now any input like easy, Medium, or hard will automatically get converted to EASY, MEDIUM, HARD before being validated and saved. This eliminates case issues entirely.

2. Case-Insensitive Custom Validator

If you need to preserve the original case of the input (not recommended for most use cases, but possible), you can write a concise custom validator that checks against the enum list without modifying the value:

const quesSchema = new mongoose.Schema({ 
  acRate: { type: Number }, 
  difficulty: { 
    type: String, 
    validate: {
      validator: (value) => {
        // Check if uppercase input matches any enum value
        return ['EASY', 'MEDIUM', 'HARD'].includes(value?.toUpperCase());
      },
      message: (props) => `${props.value} is not a valid difficulty. Must be EASY, MEDIUM, or HARD (case-insensitive)`
    }
  }, 
  title: { type: String }, 
  titleSlug: { type: String }, 
  topicTags: [ { name: { type: String } } ], 
});

Note: If you go this route, querying for difficulties will require case-insensitive regex (e.g., db.ques.find({ difficulty: { $regex: 'easy', $options: 'i' } })), which is less efficient than querying for exact matches.

3. Regex Match Validator

Another quick option is to use Mongoose's built-in match validator with a case-insensitive regex:

const quesSchema = new mongoose.Schema({ 
  acRate: { type: Number }, 
  difficulty: { 
    type: String, 
    match: {
      regex: /^(easy|medium|hard)$/i,
      message: 'Difficulty should be either EASY, MEDIUM or HARD (case-insensitive)'
    }
  }, 
  title: { type: String }, 
  titleSlug: { type: String }, 
  topicTags: [ { name: { type: String } } ], 
});

This is simple, but less flexible than the setter approach—if you ever update your enum values, you'll need to manually adjust the regex.

Final Recommendation

Stick with the setter method (option 1) for most scenarios. It keeps your data consistent, simplifies future queries, and leverages Mongoose's native enum validation without extra work.

内容的提问来源于stack exchange,提问作者Rounak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:59:08