这对我来说有点奇怪,我是mongo db的新手。
我通过NoSQLBoster控制台设置了以下验证规则:
let validator = [
{language : {
$type : "string",
$exists : true
}},
{label : {
$type : "string",
$exists : true
}},
{text : {
$type : "string",
$exists : true
}},
{order : {
$type : "int",
$exists : true
}}
];
db.runCommand( {
collMod: "profile",
validator,
validationLevel: "moderate", //off | strict
//validationAction: "warn" |"error"
})
好吧,在添加验证器之后,我尝试添加以下文档:
db.profile.insert({language: 'en', label: 'Born', text: '31 Dec 1983 - Jaén, Spain', order: 1})
我假装将所有这些字段都设为必填项。甚至提供所有它们并具有适当的类型,我总是会收到以下插入错误:
{
"message" : "write failed with error: {" +
" 'nInserted' : 0," +
" 'writeError' : {" +
" \t'code' : 121," +
" \t'errmsg' : 'Document failed validation'" +
" }" +
"}",
"stack" : "script:1:96" +
"script:1:96" +
"script:1:96" +
"script:1:96",
"code" : {
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0
}
}
现在变得好奇了... 我在做什么错了?
感谢您的时间
答案 0 :(得分:2)
我解决了我的问题。我只需要使用NumberInt()函数来包装整数。否则,它被视为浮点数。以下内容按预期工作:
db.profile.insert({language: 'en', label: 'Born', text: '31 Dec 1983 - Jaén, Spain', order: NumberInt(1)})
谢谢大家!
答案 1 :(得分:1)
这是设计使然。
详细信息
The mongo shell treats all numbers as floating-point values by default.
The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.
来源:https://docs.mongodb.com/manual/core/shell-types/#numberint