Mongoose Schema配置的max属性未生效问题咨询
问题排查与解决方案
核心问题是你使用了错误的校验属性:
max是 Number类型字段 用来校验数值上限的规则,无法对字符串长度生效- String类型字段 的长度上限校验需要使用
maxlength属性
修正后的Schema定义如下:
const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, maxlength: 150, // 替换原有的max配置 required: true, }, }, { timestamps: true, } );
如果需要自定义校验报错提示,可改成数组写法:
maxlength: [150, '内容长度不能超过150个字符']
额外注意事项
如果是通过 findByIdAndUpdate、updateOne 等更新类方法写入数据,Mongoose默认不会触发Schema校验,需要在操作时手动添加 runValidators: true 配置:
// 示例更新操作开启校验 Post.findByIdAndUpdate(postId, { content: '待更新内容' }, { runValidators: true })
内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture
相关产品推荐
相关产品推荐

