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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:48:04