简体   繁体   中英

Is it possible to add fields not present in the structure on the fly?

I was trying out mongokit and I'm having a problem. I thought it would be possible to add fields not present in the schema on the fly, but apparently I can't save the document.

The code is as below:

from mongokit import *

connection = Connection()

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

On the python shell:

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

This gives me a

StructureError: unknown fields ['foo'] in Test

I have an application where, while I have a core of fields that are always present, I can't predict what new fields will be necessary beforehand . Basically, in this case, it's up to the client to insert what fields it find necessary. I'll just receive whatever he sends, do my thing, and store them in mongodb.

But there is still a core of fields that are common to all documents, so it would be nice to type and validate them.

Is there a way to solve this with mongokit?

According to the MongoKit structure documentation you can have optional fields if you use the Schemaless Structure feature.

As of version 0.7, MongoKit allows you to save partially structured documents.

So if you set up your class like this, it should work:

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

That will require title and body but should allow any other fields to be present. According to the docs:

MongoKit will raise an exception only if required fields are missing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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