当我尝试在 MongoDB 模式中插入新文档(其中指定需要标签和属性标签)时遇到问题,我不知道是否会出现“文档验证失败”消息,因为我设置了模式标签或additionalProperties电子邮件属性中的标签。我认为这是正确的,因为它符合我的模式。
use("flow_store")
db.createCollection("people",
{
validator:
{
$jsonSchema:{
bsonType:"object",
required:["name","age","email","type"],
properties:
{
name:
{
bsonType:"string",
description:"It must be a string and is required"
},
age:
{
bsonType:"int",
description:"It must be a integer and is required"
},
email:
{
bsonType:"string",
description:"It must be an email, according with a regular expression and is required",
pattern:"^[a-zA-Z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}$"
},
type:
{
bsonType:"string",
enum:["employee","customer"],
description:"must be either 'employee' or 'customer"
},
stores: {
bsonType: "array",
items: {
bsonType: "objectId",
},
description: "must be an array of ObjectIds",
},
phone:
{
bsonType:"string",
description:"It must be a phone number and is not required"
},
address:
{
bsonType:'object',
required:["city","state","street"],
properties:
{
street:
{
bsonType:"string",
},
city:
{
bsonType:"string"
},
state:
{
bsonType:"string"
},
zip:
{
bsonType:"string"
},
},
additionalProperties:false
},
accountBalance:
{
bsonType:"number",
},
salary:
{
bsonType:"number"
},
position:
{
bsonType:"string"
},
workStores:
{
bsonType:'array',
items:
{
bsonType:'objectId'
}
}
},
additionalProperties:false
}
}
})
¿您是否发现我的文档中缺少或无法插入某些内容?
use("flow_store");
db.people.insertOne({
name: "John Doe",
age: Int32(30),
email: "[email protected]",
type: "customer",
stores: [],
address: {
street: "123 Main St",
city: "Cityville",
state: "CA",
zip: "12345"
},
accountBalance: Number(1000.50)
});
我想为我的问题找到解决方案,我会非常感谢你
是的,问题在于您的
additionalProperties:false
设置因为:
当您在 JSON 模式中指定 extraProperties: false 时,MongoDB 会拒绝包含未包含在模式属性对象中的字段的文档。由于所有对象都包含自动生成的 _id 字段,因此当您设置additionalProperties: false 时,必须在属性对象中包含 _id 字段。如果不这样做,所有文件都将被拒绝。
如果您想保留此设置,您需要手动将
_id
添加到您的架构中 properties
例如:
"_id": {
"bsonType": "objectId"
},