【问题标题】:Is it possible to add fields not present in the structure on the fly?是否可以动态添加结构中不存在的字段?
【发布时间】:2013-08-29 19:49:11
【问题描述】:

我正在尝试 mongokit,但遇到了问题。我认为可以动态添加架构中不存在的字段,但显然我无法保存文档。

代码如下:

from mongokit import *

connection = Connection()

@connection.register
class Test(Document):
    structure = {'title': unicode, 'body': unicode}

在 python 外壳上:

test = connection.testdb.testcol.Test()
test['foo'] = u'bar'
test['title'] = u'my title'
test['body'] = u'my body'
test.save()

这给了我一个

StructureError: unknown fields ['foo'] in Test

我有一个应用程序,虽然我有一个始终存在的核心字段,但 我无法事先预测需要哪些新字段。基本上,在这种情况下,由客户来插入它认为必要的字段。我只会收到他发送的任何内容,做我的事情,并将它们存储在 mongodb 中。

但仍有一个核心字段对所有文档都是通用的,因此最好键入并验证它们。

有没有办法用 mongokit 解决这个问题?

【问题讨论】:

    标签: python mongodb mongokit


    【解决方案1】:

    根据MongoKit structure documentation,如果您使用无模式结构功能,您可以有可选字段。

    从 0.7 版开始,MongoKit 允许您保存部分结构化的文档。

    所以如果你这样设置你的类,它应该可以工作:

    from mongokit import *
    class Test(Document):
        use_schemaless = True
        structure = {'title': unicode, 'body': unicode}
        required_fields = [ 'title', 'body' ]
    

    这将需要titlebody,但应该允许存在任何其他字段。根据文档:

    只有在缺少必填字段时,MongoKit 才会引发异常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多