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

如何在Mongoose的MongoDB Schema中添加独立月份存储字段

Mongoose releases 模型新增全大写月份字段方案

直接在现有Schema的字段定义中新增独立的月份字段即可,为了匹配APRIL这类全大写英文月份的存储格式,还可以加上格式自动转换、合法值校验规则,避免脏数据存入。

修改后的完整模型代码:

const releasesSchema = mongoose.Schema(
  {
    description:{
      type:String,
      required:false
    },
    artist: {
      type: String,
      required: true,
    },
    single: {
      type: String,
      required: true,
    },
    genre: {
      type: String,
      required: true,
    },
    // 新增:存储全大写格式月份
    releaseMonth: {
      type: String,
      required: false,
      uppercase: true, // 自动将传入值转为全大写,统一格式
      enum: [
        "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
        "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
      ], // 限制仅允许存入合法月份值,拦截错误拼写、不符合格式的内容
      default: null
    },
    link: {
      required: false,
      type: String,
    },
    filename: {
      required: true,
      type: String,
    },
    fileId: {
      required: true,
      type: String,
    },
    isFavourite: {
      default:false,
      required: false,
      type: Boolean,
    },
  },
  {
    timestamps: true,
  }
);
const Release = mongoose.model("releases", releasesSchema);
export default Release;

配置说明

  • 你可以根据自身命名习惯调整字段名,比如改成month也可以
  • 如果业务要求每条发行记录必须填写月份,将该字段的required属性改为true即可;如果需要兼容已存入的历史数据,保持required: false的配置,存量文档不会因为缺少该字段抛出校验错误
  • uppercase配置会自动把传入的小写、首字母大写格式的月份(比如april、April)转为全大写,不用手动写转换逻辑
  • enum枚举校验从数据层做了格式兜底,避免存入拼写错误的月份、非月份格式的字符串,保证集合内数据格式统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:15:37