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

如何在Mongoose Schema中条件设置数值字段的max校验值

实现方案

max 校验的函数上下文和你写的 required 完全一致,this 指向当前待校验的文档实例,直接按条件返回对应的上限值即可。
如果你要实现 id等于5时amount最大为100,其他id场景下不限制amount最大值,代码如下:

const schema = new mongoose.Schema({
  id: {
    type: Number
  },
  amount: {
    type: Number,
    max: function () { 
      // 满足条件返回100作为上限,不满足条件返回无穷大即不做上限校验
      return this.id === 5 ? 100 : Infinity
    },
    required: function () { return this.id === 5 }
  }
})

补充说明

  • 如果你不需要条件限制,所有场景下amount都不能超过100,直接写max: 100即可,不需要用函数返回。
  • 如果是使用findOneAndUpdate、updateMany等更新类操作触发校验,需要额外添加runValidators: true和context: 'query'配置,避免this无法获取到文档字段值导致校验失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:48:03