简体   繁体   English

在MongoDB中实施架构验证

[英]Enforcing schema validation in MongoDB

I'm looking for ways to validate that data being inserted into MongoDB matches a schema, eg has all the required fields and correct data types. 我正在寻找验证插入MongoDB中的数据是否与模式匹配的方法,例如具有所有必填字段和正确的数据类型。 I know Mongo itself is schemaless, but if I could validate the data at the application level before passing it to the Mongo driver, that'd be good. 我知道Mongo本身是无模式的,但是如果我可以在将数据传递给Mongo驱动程序之前在应用程序级别验证数据,那就太好了。

I've looked at JSON-Schema. 我看过JSON-Schema。 My biggest hesitation there is that I can only find one Java library for schema validation, and I don't know whether I should trust it, I prefer libraries backed by Apache or Google. 我最大的犹豫是我只能找到一个用于模式验证的Java库,而且我不知道是否应该信任它,我更喜欢由Apache或Google支持的库。

I've also looked at Apache Thrift, Avro, and Protocol Buffers, which aren't specifically validation frameworks, but they do each have a concept of a schema. 我还研究了Apache Thrift,Avro和Protocol Buffer,它们并不是专门的验证框架,但它们确实具有模式的概念。 I'd be interested if there's a way to piggy-back off of one of those to perform validation. 我想知道是否有一种方法可以搭载其中一种方法来执行验证。

Any suggestions? 有什么建议么? Or should I embrace the schemalessness of Mongo and not even bother trying to validate the data? 还是我应该接受Mongo的无模式性,甚至不必费心尝试验证数据?

In the upcoming Mongo 3.2 version they added document validation ( slides ). 在即将发布的Mongo 3.2版本中,他们添加了文档验证幻灯片 )。

You can specify validation rules for each collection, using validator option using almost all mongo query operators (except $geoNear , $near , $nearSphere , $text , and $where ). 您可以使用几乎所有mongo查询运算符( $geoNear$near$nearSphere$text$where除外)的validator选项为每个集合指定验证规则。 You can read more about it in one of my answers . 您可以在我的答案之一中阅读更多有关它的内容。

Not sure if you're still looking but an object document mapper (ODM) would do the trick. 不知道您是否还在寻找,但是使用对象文档映射器(ODM)可以解决问题。

I have checked out both Morphia or Spring Data - MongoDB and either would take care of your type safety concerns since they would map your documents directly to Java classes. 我已经检出了MorphiaSpring Data-MongoDB,并且它们都会处理您的类型安全问题,因为它们会将您的文档直接映射到Java类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM