Spring Data文档describes如何使用给定的$jsonSchema
创建集合,以及如何执行验证查询。
是否可以为现有集合更新$jsonSchema
? MongoTemplate.createCollection()
的现有结果导致MongoCommandException
的错误代码为48(存在集合),架构未更新。
好吧,看起来Spring Data中没有现成的方法,但是实现起来很简单:
<T> void updateSchema(MongoTemplate template,Class<T> entityClazz,MongoJsonSchema schema) {
template.executeCommand(new Document(Map.of(
"collMod",template.getCollectionName(entityClazz),"validator",schema.toDocument()
)));
}
还要记住,默认的readWrite
角色是不够的,用户需要具有collMod
特权。