如何为Mongoose自定义SchemaType配置全局默认校验及自定义错误
解决方案
要实现自定义SchemaType自带校验规则和自定义错误返回,仅需做两处核心改动:
- 在自定义类型的构造函数中调用
this.validate()注册全局校验规则,所有使用该类型的字段会自动继承校验逻辑,无需重复声明 - 类型转换失败时抛出Mongoose内置的
CastError而非普通Error,即可让自定义错误消息直接出现在错误对象顶层,无需逐层访问reason字段
完整实现代码
const mongoose = require('mongoose') const { CastError } = mongoose.Error // 内置UUIDv4格式校验规则 const UUID_V4_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/ class UUIDv4 extends mongoose.SchemaType { constructor(key, options) { super(key, options, 'UUIDv4'); // 全局注册校验规则,所有使用UUIDv4类型的字段自动生效 this.validate({ validator: val => UUID_V4_REGEX.test(val), message: props => `${props.value} 不是有效的v4版本UUID` }) } cast(val) { // 基础类型转换逻辑,可根据需求扩展比如buffer转字符串等操作 const stringVal = String(val) // 转换阶段不符合格式直接抛内置CastError if (!UUID_V4_REGEX.test(stringVal)) { throw new CastError('UUIDv4', val, this.path) } return stringVal } } // 注册到Mongoose Schema类型池 mongoose.Schema.Types.UUIDv4 = UUIDv4
使用效果
后续定义Schema时直接指定类型即可,无需额外加校验规则:
const entitySchema = new mongoose.Schema({ entityKey: { type: UUIDv4, required: true } }) const Entity = mongoose.model('Entity', entitySchema)
捕获错误时直接读取顶层消息即可,无需逐层取值:
try { const testEntity = new Entity({ entityKey: "123456789" }) await testEntity.save() } catch (e) { const errMsg = e.errors.entityKey.message console.log(errMsg) // 输出:123456789 不是有效的v4版本UUID }
内容的提问来源于stack exchange,提问作者person0
相关产品推荐
相关产品推荐

