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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With