如何在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
相关产品推荐
相关产品推荐

