【问题标题】:create mongodb collection with volidator, then insert doc error使用 volidator 创建 mongodb 集合,然后插入 doc 错误
【发布时间】:2020-06-11 11:48:43
【问题描述】:

我设法创建了一个 mongodb 集合:

db.createCollection('product', {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ['product_name', 'num'],
            properties: {
                product_name: {
                    bsonType: "string",
                    description: "must be a string"
                },
                num: {
                    minimum: 0,
                    bsonType: "int", // problem place
                    description: "must be a int and large than 0"
                }
            }
        }
    },
    validationLevel: "moderate"
})

并插入一个文档:

db.product.insertOne({product_name:'baseball',num:10})

但它不起作用,这是错误:

WriteError({
        "index" : 0,
        "code" : 121,
        "errmsg" : "Document failed validation",
        "op" : {
                "_id" : ObjectId("5ee2159b317a66d955a39c54"),
                "product_name" : "baseball",
                "num" : 10
        }
})

好像我这样创建“产品”col(使用类型:“数字”,而不是bsonType):

properties: {
     product_name: {
         type: "string",
         description: "must be a string"
        },
     num: {
         minimum: 0,
         type: "number",  //changed here
         description: "must be a int and large than 0"
        }
}

插入操作工作,为什么?

【问题讨论】:

    标签: mongodb jsonschema


    【解决方案1】:

    当您在未指定任何内容的情况下插入数值时,数值默认为double 类型。

    将插入内容更改为:

    db.product.insertOne({product_name:'baseball', num: NumberInt(10)})
    

    架构验证中的另一个注释 minimum 包含指定的值,这意味着 0 也是有效值,请将其更改为 1,而不是假设这是您正在寻找的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多