【发布时间】:2019-02-15 20:52:07
【问题描述】:
我是 MongoDB 和 NodeJS 的新手,
当我尝试使用数据类型、字符串、整数、日期和布尔值创建 JsonSchema 时,它被创建但在插入数据时总是抛出一个错误作为文档验证错误,所以我将一种数据类型的 bsonType 更改为数字,然后它开始创建集合记录,但观察是它存储为 Double 数据类型,我在 stackoverflow 的某个地方读取,它只存储这样的,但我的问题是为什么会出现这种行为?为什么在创建 JSONSCHEMA 时没有抛出错误,但在插入数据时却抛出了错误?
另外,如果我们有嵌套对象,让我们说,Customer 对象以 Address 作为嵌套对象,主对象的 int/number 值存储为 Double,而地址对象的 pincode 内部存储为 Int32。这也是非常令人困惑的。这些对象之间有什么区别,但模式的结构是相同的。
还有哪些其他方法可以为 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" : "invoice.companysInt1s1"
}
}
]
> db.companysInt1s1.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
我是否遗漏了某些东西或我应该遵循的任何其他文档?感谢您的指导...
【问题讨论】: