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

MongoDB单字段能否同时设置字符串与Null两种验证类型?

MongoDB字段验证:同时允许字符串与Null类型

完全可以实现让字段t1同时支持字符串(string)和Null两种类型,有两种常见的修改方式:

方式一:直接指定多种BSON类型

将t1的bsonType设置为包含"string"和"null"的数组即可,示例规则如下:

{
  "$jsonSchema": {
    "bsonType": "object",
    "title": "Validations",
    "properties": {
      "t1": {
        "bsonType": ["string", "null"],
        "description": "label field can be a string (min. 1 character) or null"
      }
    }
  }
}

方式二:用anyOf细化不同类型的验证规则

如果需要对字符串类型单独设置长度要求(比如原规则里的最小1字符),而Null类型不需要验证,可以用anyOf分别定义两种类型的规则,这样更严谨:

{
  "$jsonSchema": {
    "bsonType": "object",
    "title": "Validations",
    "properties": {
      "t1": {
        "anyOf": [
          {
            "bsonType": "string",
            "minLength": 1,
            "description": "label field must be at least 1 character in length"
          },
          {
            "bsonType": "null",
            "description": "label field can be null"
          }
        ]
      }
    },
    // 如果要求字段必须存在(允许为null值),可以添加required数组
    "required": ["t1"]
  }
}

以上两种方式都能实现需求:t1字段既可以是满足长度要求的字符串,也可以直接赋值为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:02:36