create mongodb collection with volidator, then insert doc error

Viewed 25

I manged to create a mongodb collection as this:

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"
})

and insert one doc as:

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

but it not work, this is the error:

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

as if I create "product" col as this(use type:"number",not 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"
        }
}

insert op work, why?

1 Answers

Numerical values are by default of type double when you insert them without specifying anything.

Change your insert into:

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

One more note minimum in schema validation includes the value specified meaning that 0 is also a valid value, change it to 1 instead assuming that's the behaviour you're looking for.

Related