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

如何在MongoDB Atlas JSON Schema中正确定义RealmList<String>?

问题

我有一个用Kotlin编写的Realm模型类Note,需要在MongoDB Atlas中生成对应的JSON Schema。但在定义RealmList<String>类型的images字段时,将bsonType设为"array"会报错,请问应如何正确定义?

模型类代码

class Note : RealmObject {
    @PrimaryKey
    var _id: ObjectId = ObjectId.create()
    var title: String = ""
    var description: String = ""
    var images: RealmList<String> = realmListOf()
    var date: RealmInstant = RealmInstant.from(System.currentTimeMillis(),0)
}

当前Schema代码

{
  "bsonType": "object",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "title": {
      "bsonType": "string"
    },
    "description": {
      "bsonType": "string"
    },
    "images": {
      "bsonType": "array"
    },
    "date": {
      "bsonType": "date"
    }
  },
  "required": [
    "_id",
    "title",
    "description",
    "images",
    "date"
  ],
  "title": "Note"
}
解决方案

报错的核心原因是MongoDB Atlas的JSON Schema对数组类型要求明确指定元素的bsonType,仅声明"bsonType": "array"是不完整的,无法验证数组内元素的合法性。

针对RealmList<String>类型的images字段,正确的Schema定义需要添加items属性,指定数组元素的类型为string。修改后的完整Schema如下:

{
  "bsonType": "object",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "title": {
      "bsonType": "string"
    },
    "description": {
      "bsonType": "string"
    },
    "images": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      }
    },
    "date": {
      "bsonType": "date"
    }
  },
  "required": [
    "_id",
    "title",
    "description",
    "images",
    "date"
  ],
  "title": "Note"
}

补充说明:你的date字段使用RealmInstant类型,在Realm中会被序列化为MongoDB的date类型,当前Schema里的定义是正确的,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:55:16