MongoEngine / MongoEngine/mongoengine

MongoEngine needs lazy loading for references (aka the NotRegistered exception)

Open
#490 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

MongoEngine provides two different ways of defining relationships, one by passing the actual class object of the related object, or by passing the string name or qualified class name, which would seem to indicate that MongoEngine implements lazy loading of relationships, like Django.

Unfortunately, that's not true. Related classes must always be defined before being referenced in a relationship.

You can easily reproduce the problem like this:

class ModelOne(mongoengine.Document):
    subfield = mongoengine.EmbeddedDocumentField('ModelTwo')

class ModelTwo(mongoengine.EmbeddedDocument):
    pass

Simply changing the order of the above classes fixes the issue:

class ModelTwo(mongoengine.EmbeddedDocument):
    pass

class ModelOne(mongoengine.Document):
    subfield = mongoengine.EmbeddedDocumentField('ModelTwo')

It seems strange that passing a string as a parameter to EmbeddedDocumentField is accepted, because the actual functionality contradicts the need for such a thing.

See here in the Django documentation:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...

class Manufacturer(models.Model):
# ...

The idea is that Django does lazy-loading to deal with things not being imported in the right order. Is there a way that we could implement this in MongoEngine?

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 with the two-class reproduction in the issue and trace how EmbeddedDocumentField resolves the string reference. Add focused coverage for defining ModelOne before ModelTwo, then verify that referenced classes can be resolved regardless of declaration order without breaking existing relationship behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.