Skip to content
namlook edited this page Aug 22, 2011 · 3 revisions

Referencing other documents

Just like every databases, you can reference an object with MongoDB.

Other documents can be referenced via their id (which is often an ObjectId).

But sometimes working with ObjectIds is not so practical and we need the object instead. It's a good practice to create a property for each references:

from mongolite import Document

@connection.register
class Blog(Document):
    __database__ = 'tutorial'
    __collection__ = 'blogs'
    skeleton = {
        "title": unicode
    }

@connection.register
class BlogPost(Document):
    __database__ = 'tutorial'
    __collection__ = 'blogposts'
    skeleton = {
        'title':unicode,
        'blog': ObjectId,
    }

    @property
    def blog(self):
        if getattr(self, "blog", {}).get("_id") != self["blog"]:
            self.blog = self.connection.Blog.get_from_id(self["blog"])
        return self.blog

So instead of having the following code:

>>> blog = connection.Blog.get_from_id(blogpost["blog"])

We get:

>>> blog = blogpost.blog

Using properties is very handy if you want to export your document in json.

FAQ

I'd like to get the reference of my object

You can get the dbref of a document with the get_dbref() method. dereference() allow to get a document from a dbref. You can pass a document to tell mongolite to what model it should dereferenced:

>>> dbref = blogpost.get_dbref()
>>> raw_doc = con.tutorial.dereference(dbref) # the result is a regular dict
>>> doc = con.tutorial.dereference(dbref, BlogPost) # the result is a BlogPost instance

Clone this wiki locally