【问题标题】:MongoDb Document Failed validation [duplicate]MongoDb文档验证失败[重复]
【发布时间】:2020-03-16 05:07:04
【问题描述】:

我正在尝试在我的测试集合中使用 JSON 模式验证器。它有 anyOf 验证规则,应该接受 foobar,我的理解是否有效且正确。

Validation:

{
  $jsonSchema: {
    bsonType: 'object',
    additionalProperties: false,
    anyOf: [
      {
        bsonType: 'object',
        properties: {
          foo: {
            bsonType: 'string'
          }
        },
        additionalProperties: false
      },
      {
        bsonType: 'object',
        properties: {
          bar: {
            bsonType: 'string'
          }
        },
        additionalProperties: false
      }
    ],
    properties: {
      _id: {
        bsonType: 'objectId'
      }
    }
  }
}

Command to insert a document:
rs0:PRIMARY> db.myColl.insert([{foo:"123"}])

Error given:

BulkWriteResult({
    "writeErrors" : [
            {
                    "index" : 0,
                    "code" : 121,
                    "errmsg" : "Document failed validation",
                    "op" : {
                            "_id" : ObjectId("6ee51b4766ba25a01fbcf8u9"),
                            "foo" : "test123"
                    }
            }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

据我所知,MongoDB 支持 JSON Schema 草案 4,指定为 here

为什么它仍然给我一个错误代码 121(文档验证失败)?

我错过了什么吗?

提前致谢。

【问题讨论】:

  • 他们绝对是相似的@Relequestual!我想要做的是与 _id 一起拥有许多基本属性,然后除了基本字段之外,只允许 foo 或 bar 作为字段,可以这么说。这可能吗?谢谢。
  • 阅读我对另一个问题的回答,看看是否有帮助。解决方案中的模式与您的模式相同。之后,如果您认为这个问题仍然不同,请告诉我 =]

标签: mongodb validation schema jsonschema json-schema-validator


【解决方案1】:

正如@Relequestual 所述,here 中的帖子帮助我解决了我的问题。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    相关资源
    最近更新 更多