gpt4 book ai didi

mongodb - 使用 volidator 创建 mongodb 集合,然后插入文档错误

转载 作者:行者123 更新时间:2023-12-04 09:41:10 24 4
gpt4 key购买 nike

我设法创建了一个 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
}
})

就像我创建“产品”列一样(使用类型:“数字”,而不是 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"
}
}

插入操作工作,为什么?

最佳答案

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

将您的插入更改为:

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

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

关于mongodb - 使用 volidator 创建 mongodb 集合,然后插入文档错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62323691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com