MongoDB + NodeJS:文档验证和数据类型行为失败
我是MongoDB和NodeJS的新手,
当我尝试使用数据类型,字符串,整数,日期和布尔值创建JsonSchema时,它会被创建,但在插入数据时总是抛出错误作为文档验证错误,所以我将一种数据类型的bsonType更改为数字,然后它开始创建集合记录,但观察是它存储为Double数据类型,我在stackoverflow中的某处读取,它只存储,但我的问题是为什么这种行为?为什么在创建JSONSCHEMA时没有出现错误,但是在插入数据时它是在抛出?
另外,如果我们有嵌套对象让我们说,Customer对象使用Address作为嵌套对象,则主对象的int / number值存储为Double,其中存储为Int32的地址对象的pincode内部。这也很令人困惑。这些对象之间的区别是什么,但架构的结构是相同的。
为MongoDB实现和使用适当的验证模式的其他方法有哪些。
>
db.getCollectionInfos({name:"companysInt1s1"})
[
{
"name" : "companysInt1s1",
"type" : "collection",
"options" : {
"validator" : {
"$jsonSchema" : {
"bsonType" : "object",
"required" : [
"tin"
],
"properties" : {
"tin" : {
"bsonType" : "int",
"minLength" : 2,
"maxLength" : 11,
"description" : "must be a string and is not required, should be 11 characters length"
}
}
}
}
},
"info" : {
"readOnly" : false,
"uuid" : UUID("27cba650-7bd3-4930-8d3e-7e6cbbf517db")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "invoicepanysInt1s1"
}
}
]
> dbpanysInt1s1.insertOne({tin:22222})
2019-02-14T15:04:28.712+0530 E QUERY [js] WriteError: Document failed validation :
WriteError({
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5c653624e382c2ec16c16893"),
"tin" : 22222
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
我错过了什么或者我应该遵循的任何其他文件吗?感谢您的指导......
回答如下:你需要插入NumberInt
。
当你运行它
dbpanysInt1s1.insertOne({tin:22222})
你实际上插入tin
作为浮动。
所以正确的方法是
dbpanysInt1s1.insertOne({tin: NumberInt(22222) })