MongoEngine / MongoEngine/mongoengine

Field accessability in DynamicDocuments

Open
#322 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

A DynamicDocument take arbitrary named fields, but there is a problem with the mongoengine API:

class Test(DynamicDocument):
    name = StringField()

t = Test()

Let's say I would like a dynamic field called "validate", this is what happens:

Try number one:
t['validate'] = "foo"

Throws a KeyError exception, which I find odd, since I have a DynamicDocument.

Try number two:
t.validate = "foo"
t.save()

Throws a TypeError exception, because t.validate is no longer a function.

Try number three:
Test.from_json('{"validate": "foo"}').save()

Throws also a TypeError exception...

Try number four:
t.update(set__validate="foo")
t['validate']

Throws yet another KeyError exception, so the custom field data is lost.

And here my suggestion for an API change:

DynamicDocument.setitem(self, name) should be aware if it acts in a DynamicDocument and accept keys that are not part of self._fields.

BaseDocument.setattr(self, name, value) must only be used as a syntactical-sugar, since it can not always represent all fields.

The dictionary-style field access should be the preferred access style, since not all fields can be mapped as class attributes.

Document.from_json(cls, json_data) should also use the dictionary-style field access, so it can be safely applied to DynamicDocuments.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading DynamicDocument.setitem, BaseDocument.setattr, and Document.from_json, focusing on how dynamic field names are handled and where reserved names fail. Done means dictionary-style access and JSON loading preserve dynamic fields such as "validate" without raising the reported exceptions or losing the field data.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
database
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
39/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.