我在 docker 中运行 MongoDB (v 6.0.4)。我通过 mongo 脚本创建了一个带有验证模式的集合(脚本文件 - test.js 使用波纹管命令运行,该文件通过卷链接)
mongosh --username username--password password --authenticationDatabase admin ./test.js
test.js内容:
db.createCollection("faculties", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "shortcut"],
properties: {
name: {
bsonType: "string",
minLength: 0,
description: "Faculty name"
},
shortcut: {
bsonType: "string",
minLength: 0,
description: "Faculty name shorcut"
}
}
}
}
});
当我尝试将有效文档插入集合时,验证有效。当我添加无效的时,验证也有效(没有添加文档,抛出错误)。我面临的问题是发生错误时应该记录其他信息(根据 this )。这在我做了 written here -> 之后才有效 运行 mongo shell,为我想要的数据库运行波纹管命令,然后重新启动
db.adminCommand( { setFeatureCompatibilityVersion: “5.0” } )
之后,当我尝试通过
在 mongo shell 中插入无效文档时db.faculties.insertOne({})
记录包含有关验证失败的附加信息的正确错误
错误应该是这样的
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("6457f574543ac2df89f1254e"),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'required',
specifiedAs: { required: [ 'name', 'shortcut' ] },
missingProperties: [ 'name', 'shortcut' ]
}
]
}
}
我得到的错误:
MongoServerError: Document failed validation
所以验证抛出错误适用于 mongo shell(在使用 db.adminCommand 命令之后),但是当我尝试通过 mongo 脚本插入相同的文档时,不会抛出附加信息。如何为 mongo 脚本启用相同的功能?