Java 使用Spring定义Mongo模式验证

Java 使用Spring定义Mongo模式验证,java,spring,mongodb,spring-boot,spring-data-mongodb,Java,Spring,Mongodb,Spring Boot,Spring Data Mongodb,我想在Mongo中使用Spring boot和JSON模式验证器选项定义一个集合(),我不想要JSR-303 Bean验证(这不是一个有效的答案),而是在创建集合时,使用CollectionFos()定义一个显示在JSON中的选项 例如,如果我定义一个帐户模型类,如下所示: public class Account { @Id private String id; private String name; private String surname; @NotNull private

我想在Mongo中使用Spring boot和JSON模式验证器选项定义一个集合(),我不想要JSR-303 Bean验证(这不是一个有效的答案),而是在创建集合时,使用CollectionFos()定义一个显示在JSON中的选项

例如,如果我定义一个帐户模型类,如下所示:

public class Account {

@Id
private String id;

private String name;

private String surname;

@NotNull
private String username;
}
我希望集合使用db.getCollectionFos()具有类似以下内容的json:

[
{
    "name" : "account",
    "type" : "collection",
    "options" : {
        "validator" : {
            "$jsonSchema" : {
                "bsonType" : "object",
                "required" : [ 
                    "username"
                ]
            }
        }
    },
    "info" : {
        "readOnly" : false,
        "uuid" : UUID("979cdc4b-d6f3-4aef-bc89-3eee812773a5")
    },
    "idIndex" : {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "databaseName.account"
    }
}
]

该过程可能类似于spring.jpa.hibernate.ddl-auto=create,因为它在模式级别定义规则,而不类似于Bean validator,后者在应用程序级别定义规则。

2.1版起,spring Data MongoDB支持JsonSchema。详情请参阅。
您可以使用下面这样的生成器来定义模式

MongoJsonSchema模式=MongoJsonSchema.builder()
.必填(“用户名”)
.properties(JsonSchemaProperty.string(“用户名”))
.build();
createCollection(“account”,CollectionOptions.empty().schema(schema));
在编写json模式时,不支持从域类型创建json模式。 但是,您可能希望加入讨论和/或提供尝试的快照

该建议通过调用类似于
MongoJsonSchema schema=schemaCreator.createSchemaFor(DomainType.class)的东西,将
DomainType
转换为
MongoJsonSchema

公共类域类型{
私有最终字符串requiredDirectorArg;
私有final@Nullable字符串nullableCtorArg;
私有字符串可选参数;
公共域类型(字符串RequiredTorArg,@Nullable字符串NullableTorArg){
this.requiredCtorArg=requiredCtorArg;
this.nullableCtorArg=nullableCtorArg;
}
//省略getter/setter
}

MongoDB中服务器上的模式验证是“非常新的”,而
$jsonSchema
“查询操作符”本身在野外的流通时间实际上只有几个月。在SpringMongo中添加“新特性”传统上是“慢节奏的”,但它不是官方的MongoDB项目,因此是“爱的社区劳动”。如果您没有看到文档中提到的功能,那么它就不存在了。他们可能只是接受一个自愿的请求。你的问题是什么?@BrentR我希望spring data mongo从modelHi@Christoph开始自动定义JSON模式,谢谢你的回答!我有一个问题:为什么您决定将@Nullable设置为定义不需要的参数,而不是像Hibernate那样定义@NotNull参数?此外,是否有任何正在进行的任务也支持特殊关键字(如字符串模式)?请让我们讨论在中导出模式的要求/决策。
{
    'type' : 'object',
    'required' : ['requiredCtorArg'],
    'properties' : {
        'requiredCtorArg' : { 'type' : 'string' },
        'nullableCtorArg' : { 'type' : 'string' },
        'optionalArg' : { 'type' : 'string' }
     }
}