Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoengine- what do referencefield store

In mongoengine what value must be set into ReferenceField. I mean should we provide in "ObjectId" of the document to which the reference is to be made. For example,

class Bar(Document):
    content = StringField()
    foo = ReferenceField('Foo')

The object of class Bar should have what value set to in "foo" attribute. Should it be the ObjectId of some document in 'Foo' collection? Also can I set any other unique field as a value in reference field mentioning which field it is?

like image 547
Sushant Gupta Avatar asked Aug 08 '12 16:08

Sushant Gupta


2 Answers

Before MongoEngine version 0.8, it stores a DBRef by default. For 0.8 and later, it stores an ObjectId by default.

There's a dbref parameter that you should use when creating the ReferenceField (explicit is better than implicit):

class Bar(Document):
    content = StringField()
    foo = ReferenceField('Foo', dbref = True)   # will use a DBRef
    bar = ReferenceField('Bar', dbref = False)  # will use an ObjectId

Here's the documentation for the ReferenceField.

I have version 0.7.9 installed, and when I create a ReferenceField without the dbref parameter, I get the following warning:

[...]/lib/python2.7/site-packages/mongoengine/fields.py:744: FutureWarning:
ReferenceFields will default to using ObjectId  strings in 0.8, set DBRef=True
if this isn't desired
warnings.warn(msg, FutureWarning)
like image 131
MiniQuark Avatar answered Oct 06 '22 11:10

MiniQuark


It's stores a DBRef, you just need to pass a Foo instance and it will be converted automatically. See the section in the docs: https://mongoengine-odm.readthedocs.io/guide/defining-documents.html?highlight=referencefield

like image 45
Ross Avatar answered Oct 06 '22 13:10

Ross